Categories
jQuery

jQuery — Key Events and Select Element by Type

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.keypress()

We can use the keypress method to listen to keypress events or trigger it.

For example, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keypress event on the input by writing:

$("#target").keypress(function() {
  console.log("Handler for .keypress() called.");
});

We can also trigger the keypress event when we click on the div with ID other by writing:

$("#target").keypress(function() {
  console.log("Handler for .keypress() called.");
});$("#other").click(function() {
  $("#target").keypress();
});

.keyup()

The .keyup() method lets us listen to the keyup event or trigger it.

For instance, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keyup event on the input by writing:

$("#target").keyup(function() {
  console.log("Handler for .keypress() called.");
});

We can also trigger the keyup event when we click on the div with ID other by writing:

$("#target").keyup(function() {
  console.log("Handler for .keypress() called.");
});$("#other").click(function() {
  $("#target").keyup();
});

:lang() Selector

The :lang selector lets us select all elements of the specified language.

For example, if we have the following HTML:

<div lang="en-us">red
  <div>white
    <div>and blue</div>
  </div>
</div>
<div lang="es-es">rojo
  <div>amarillo
    <div>y rojo</div>
  </div>
</div>

And CSS:

.spain {
  background-color: red;
  color: #ff0;
}.usa {
  background-color: red;
  color: #fff;
}

Then we can add the different classes to the div with different lang attribute values by writing:

$("div:lang(en-us)").addClass("usa");
$("div:lang(es-es)").addClass("spain");

.last()

We can get the last element in a set of matched elements with the .last method.

For example, if we have:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Then we add a red background to the last li by writing:

$("li").last().css("background-color", "red");

We get the li's and then call last to get the last one.

:last-child Selector

The :last-child selector selects all elements that are the last child of the parent.

For example, if we have the following HTML:

<div>
  <span>John,</span>
  <span>Karl,</span>
  <span>Brandon,</span>
  <span>Sam</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Ralph,</span>
  <span>David</span>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("div span:last-child")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

:last-of-type Selector

We can get the last element of a given type with the :last-pf-type selector.

For example, if we have the following HTML:

<div>
  <span>Corey,</span>
  <span>Yehuda,</span>
  <span>Adam,</span>
  <span>Todd</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Tim,</span>
  <b>Nobody</b>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("span:last-of-type")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

Conclusion

We can listen to key events and get elements by type with jQuery.

Categories
jQuery

jQuery — Deferred and Data

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.data()

We can store data within matched elements with the data method.

For example, we can write the following HTML:

<span></span>

Then use data to store and get the data as follows:

$("body").data("foo", 52);
$("span").first().text($("body").data("foo"));

We save the data with key 'foo' and value 52 in the first line.

Then in the 2nd line, we get the data and put it in the span .

.dblclick()

The .dblclick() method binds an event handler to the dblclick event or trigger the event on an element.

For example, if we have the following HTML:

<div id="target">
  Double-click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to double clicks on the div with ID target by writing:

$("#target").dblclick(function() {
  alert("Handler for .dblclick() called.");
});

We can also trigger a double click on the div with ID target when we click on the div with ID other by writing:

$("#target").dblclick(function() {
  alert("Handler for .dblclick() called.");
});$("#other").click(function() {
  $("#target").dblclick();
});

deferred.always()

deferred.always() adds a callback to be called when the deferred object is resolved or rejected.

For example, we can write:

$.get("foo.php").always(function() {
  alert("$.get completed");
});

to call the alert when we make a GET request for foo.php .

deferred.catch()

The deferred.catch method adds a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("foo.php")
  .then(function() {
    alert("$.get succeeded");
  })
  .catch(function() {
    alert("$.get failed!");
  });

or:

(async () => {
  try {
    const res = await $.get("foo.php")
  } catch (error) {
    alert("$.get failed!");
  }
})()

$.get returns a thenable object so it works with async and await .

deferred.done()

The deferred.done() method lets us add a callback that’s called when the deferred object is resolved.

For example, we can write:

$.get("https://jsonplaceholder.typicode.com/todos/1")
  .done(function() {
    alert("$.get succeeded");
  });

to make a GET request https://jsonplaceholder.typicode.com/todos/1 and add run something after that.

deferred.fail()

The deferred.fail() method lets us add a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("test.php")
  .done(function() {
    alert("$.get succeeded");
  })
  .fail(function() {
    alert("$.get failed!");
  });

to add that.

deferred.pipe()

We can use the deferred.pipe() method to filter and chain deferred objects.

It returns another deferred object.

We can use it by writing:

const defer = $.Deferred(),
  filtered = defer.pipe(function(value) {
    return value * 2;
  });defer.resolve(5);
filtered.done(function(value) {
  alert(value);
});

We call defer.pipe with a callback that takes the resolved value from the defer object, multipole by it by 2, and return it in the callback.

Then we call defer.resolve(5) to pass 5 as the value of value in the pipe callback.

And we get the finalvalue in the done callback, which is 10.

We can chain deferred by writing:

const url = 'https://jsonplaceholder.typicode.com/posts/1';
const url2 = 'https://jsonplaceholder.typicode.com/posts/2';
const request = $.ajax(url, {
    dataType: "json"
  })
  .pipe(function(data) {
    console.log(data)
    return $.ajax(url2);
  })
  .done(function(data) {
    console.log(data)
  });

We call pipe on the first deferred object returned by $.ajax and then call done to get the data from the 2nd $.ajax call.

Conclusion

We can work with deferred objects with various jQuery methods.

Categories
jQuery

jQuery — Widths and Wrapping

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.width()

The .width() method gets the current computed width for the first element in the set of matched elements or set the width of every matched element.

For example, we can write:

console.log($(window).width());

to log the width of the window.

To set the widths of the divs given the following HTML:

<div>d</div>  
<div>d</div>  
<div>d</div>  
<div>d</div>  
<div>d</div>

And CSS:

div {  
  width: 70px;  
  height: 50px;  
  float: left;  
  margin: 5px;  
  background: red;  
  cursor: pointer;  
}

We can add click handlers to the divs and change the width inside by writing:

const modWidth = 50;  
$("div").one("click", function() {  
  $(this).width(modWidth)  
});

.wrap()

The .wrap() method lets us wrap an element with a wrapper element.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap each div with the class inner with a div with class new by writing:

$(".inner").wrap("<div class='new'></div>");

.wrapAll()

The .wrapAll() method lets us wrap an HTML structure around all elements in the set of matched elements.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap a div with class new around all the divs with class inner by writing:

$(".inner").wrapAll("<div class='new' />");

.wrapInner()

We can wrap an HTML structure around the content of each element in the set of matched elements with the wrapInner method.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap the content of each div with class inner with a div with class new by writing:

$(".inner").wrapInner("<div class='new'></div>");

Conclusion

We can wrap elements with other elements with jQuery.

Also, we can get and set the width of the elements.

Categories
jQuery

jQuery — Wrapping, Visibility, and Delegation

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.triggerHandler()

The .triggerHandler() method lets us run all handlers attached to an event for an element.

For example, if we have:

<button id="new">.triggerHandler( "focus" )</button><br><br>

<input type="text" value="To Be Focused">

Then we can trigger the focus event when we click on the button by writing:

$("#new").click(function() {
  $("input").triggerHandler("focus");
});

$("input").focus(function() {
  $("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});

We show the Focused! text when we click on the button as the input is focused.

.unbind()

The .unbind() method removes a previous attached event handler from the elements.

For example, if we have:

<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div id="theone"></div>

Then we can bind and unbind the click handler for the div with id theone by writing:

function aClick() {
  $("div").show().fadeOut("slow");
}

$("#bind").click(function() {
  $("#theone")
    .bind("click", aClick)
    .text("Can Click!");
});
$("#unbind").click(function() {
  $("#theone")
    .unbind("click", aClick)
    .text("Does nothing...");
});

We bind and unbind the click events on the div in the click handlers for the buttons.

.undelegate()

The .undelegate() method removes a handler from the event for all elements which match the current selector which match the current selector based on the root element.

For example, if we have:

<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div id="theone"></div>

Then we can bind and unbind the click handler from the div with ID theone by writing:

function aClick() {
  $("div").show().fadeOut("slow");
}

$("#bind").click(function() {
  $("body")
    .delegate("#theone", "click", aClick)
    .find("#theone")
    .text("Can Click!");
});

$("#unbind").click(function() {
  $("body")
    .undelegate("#theone", "click", aClick)
    .find("#theone")
    .text("Does nothing...");
});

.unwrap()

The .unwrap() method removes the parent of the set of matched elements from the DOM.

For example, if we have:

<button>wrap/unwrap</button>
<p>Hello</p>
<p>World</p>

We can toggle the wrapping and unwrapping of the div around the p elements by writing:

const pTags = $("p");
$("button").click(function() {
  if (pTags.parent().is("div")) {
    pTags.unwrap();
  } else {
    pTags.wrap("<div></div>");
  }
})

wrap all wrap each p element in its own div.

.val()

The .val() method gets the current value of the first element in the set of matched elements.

We can also use it to set th value of every matched element.

For example, if we have:

<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>

<select id="multiple" multiple="multiple">
  <option selected="selected">Multiple</option>
  <option>Multiple2</option>
  <option selected="selected">Multiple3</option>
</select>

Then we can get the value selected from the select element by writing:

function displayVals() {
  const singleValues = $("#single").val();
  const multipleValues = $("#multiple").val() || [];
  console.log(singleValues, multipleValues)
}

$("select").change(displayVals);

For example, if we have:

<input type="text" value="some text">

Then we can get the value from the input as we type by writing:

$("input")
  .keyup(function() {
    const value = $(this).val();
    console.log(value);
  })
  .keyup();

:visible Selector

The :visible selector lets us select all elements that are visible.

For example, if we have the following HTML:

<button>Show hidden</button>
<div></div>
<div class="starthidden"></div>
<div></div>
<div></div>
<div style="display:none;"></div>

And CSS:

div {
  width: 50px;
  height: 40px;
  margin: 5px;
  border: 3px outset green;
  float: left;
}

.starthidden {
  display: none;
}

Then we can show all the divs that are hidden when we click on the button by writing:

$("div:visible").click(function() {
  $(this).css("background", "yellow");
});
$("button").click(function() {
  $("div:hidden").show("fast");
});

And when we click on the visible divs, we see a yellow background.

Conclusion

We can trigger handlers, unbind events, and make elements visible with jQuery.

Categories
jQuery

jQuery — Events and Toggles

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.submit()

The .submit() method lets us bind an event handler to the submit JavaScript event or trigger the event on an element.

For example, if we have:

<form id="target" action="destination.html">
  <input type="text" value="Hello there">
  <input type="submit" value="Go">
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the submit event on the form by writing:

$("#target").submit(function(event) {
  console.log("Handler for .submit() called.");
  event.preventDefault();
});

We can also trigger the submit event by writing:

$("#other").click(function() {
  $("#target").submit();
});

:submit Selector

The :submit selector lets us select all elements of type submit.

For example, if we have:

<form id="target" action="destination.html">
  <input type="text" value="Hello there">
  <input type="submit" value="Go">
</form>

Then we can add a background and border on the submit button by writing:

$("input:submit")
  .css({
    background: "yellow",
    border: "3px red solid"
  })
  .end();

:target Selector

The :target selector selects the target element indicated by the fragment identifier of the document’s URI.

For example, if we go to https://example.com/#foo, then, $(“p:target”) selects the p element with ID foo .

.text()

The .text method gets the combined text contents of each element in the set of matched elements, including their descendants.

For example, if we have:

<p><b>Test</b> Paragraph.</p>
<p></p>

Then if we write:

console.log($("p").first().text())

We get 'Test Paragraph.’ logged.

:text Selector

The :text selector lets us select all input elements of type text .

For example, if we have:

<form id="target" action="destination.html">
  <input type="text" value="Hello there">
  <input type="submit" value="Go">
</form>
<div id="other">
  Trigger the handler
</div>

Then we can add a background and border to the text input box by writing:

$("form input:text").css({
  background: "yellow",
  border: "3px red solid"
});

.toArray()

The .toArray() method retrieves all elements contained in the jQuery set as an array.

For example, if we have:

<div>One</div>
<div>Two</div>
<div>Three</div>

Then we can get the divs and put them into an array by writing:

console.log($("div").toArray());

.toggle()

The .toggle() method displays or hide the matched elements.

For example, if we have:

<div id="clickme">
  Click here
</div>
<img id="book" src="https://i.picsum.photos/id/23/200/200.jpg?hmac=IMR2f77CBqpauCb5W6kGzhwbKatX_r9IvgWj6n7FQ7c">

Then we can make the image toggle between on and off when we click the Click here button by writing:

$("#clickme").click(function() {
  $("#book").toggle("slow", function() {
    // Animation complete.
  });
});

.toggleClass()

The .toggleClass() method lets us add or remove one or more classes from each element in the set of matched elements.

For example, if we have the following HTML:

<p class="blue">Click to toggle</p>

And CSS:

p {
  margin: 4px;
  font-size: 16px;
  font-weight: bolder;
  cursor: pointer;
}

.blue {
  color: blue;
}

.highlight {
  background: yellow;
}

Then we can toggle the highlight class on the p element by writing:

$("p").click(function() {
  $(this).toggleClass("highlight");
});

.trigger()

The .trigger() method runs all handlers and behaviors attached to the matched elements for the given event type.

For example, if we have:

<button>Button #1</button>
<button>Button #2</button>

Then we can trigger the click on the first button when we click on the second button by writing:

$("button").first().click(function() {
  console.log('first button clicked');
});

$("button").last().click(function() {
  $("button").first().trigger("click");
});

Conclusion

We can trigger events and toggle classes using jQuery.