Categories
jQuery

jQuery — Select Elements and Remove Event Listeners

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.

:not() Selector

The :not selector selects all elements that don’t match a given selector.

For example, if we have:

<div>
  <input type="checkbox" name="a">
  <span>Mary</span>
</div>
<div>
  <input type="checkbox" name="b">
  <span>lcm</span>
</div>
<div>
  <input type="checkbox" name="c" checked="checked">
  <span>Peter</span>
</div>

Then we add a yellow background to all the checkboxes that are unchecked by writing:

$("input:not(:checked) + span").css("background-color", "yellow");

:nth-child() Selector

The :nth-child() selector lets us select all elements that are the nth-child of their parent.

For example, if we have:

<div>
  <ul>
    <li>John</li>
    <li>Karl</li>
    <li>Brandon</li>
  </ul>
</div>
<div>
  <ul>
    <li>Sam</li>
  </ul>
</div>
<div>
  <ul>
    <li>John</li>
    <li>Jane</li>
    <li>Ralph</li>
    <li>David</li>
  </ul>
</div>

Then we add a span to the name that is in the 2nd li of each ul by writing:

$("ul li:nth-child(2)").append("<span> - 2nd!</span>");

:nth-last-child() Selector

The :nth-last-child selector lets us select all elements that are the nth-child of their parent.

For example, if we have:

<div>
  <ul>
    <li>John</li>
    <li>Karl</li>
    <li>Brandon</li>
  </ul>
</div>
<div>
  <ul>
    <li>Sam</li>
  </ul>
</div>
<div>
  <ul>
    <li>John</li>
    <li>Jane</li>
    <li>Ralph</li>
    <li>David</li>
  </ul>
</div>

Then we get the 2nd last li in each ul and add a child span to it by writing:

$("ul li:nth-last-child(2)").append("<span> - 2nd to last!</span>");

:nth-last-of-type() Selector

The :nth-last-of-type selector lets get the last element of the given type.

For example, if we have:

<div>
  <ul>
    <li>John</li>
    <li>Karl</li>
    <li>Brandon</li>
  </ul>
</div>
<div>
  <ul>
    <li>Sam</li>
  </ul>
</div>
<div>
  <ul>
    <li>John</li>
    <li>Jane</li>
    <li>Ralph</li>
    <li>David</li>
  </ul>
</div>

Then we can get the 2nd last li s in the ul and add a span in them by writing:

$("ul li:nth-last-of-type(2)").append("<span> - 2nd to last!</span>");

:nth-of-type() Selector

The :nth-of-type selector selects all elements that are the nth child of their parent in relation to siblings with the same element name.

For example, if we have:

<div>
  <span>John</span>,
  <b>Kim</b>,
  <span>Adam</span>,
  <b>Rafael</b>,
  <span>Oleg</span>
</div>
<div>
  <b>Dave</b>,
  <span>Ann</span>
</div>
<div>
  <i><span>Maurice</span></i>,
  <span>Richard</span>,
  <span>Ralph</span>,
  <span>Jason</span>
</div>

Then we get the 2nd sibling span and add another span into it by writing:

$("span:nth-of-type(2)")
  .append("<span> is 2nd sibling span</span>")
  .addClass("nth");

.odd()

We can reduce the set of matched elements to the odd ones in the set with the odd selector.

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 select the li ‘s with an odd index by writing:

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

We add a red background to the 2nd and 4th li since the index starts at 0.

.off()

The .off() select removes an event handler.

For example, if we have:

<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div style="display:none;">Click!</div>

Then we can use the off method to remove a click handler by writing:

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

$("#bind").click(function() {
  $("body")
    .on("click", "#theone", flash)
    .find("#theone")
    .text("Can Click!");
});
$("#unbind").click(function() {
  $("body")
    .off("click", "#theone", flash)
    .find("#theone")
    .text("Does nothing...");
});

The click listener for the button with ID unbind has the off method to remove the flash function as the body’s click handler.

Conclusion

We can select elements with various selectors and remove event listeners with jQuery.

Categories
jQuery

jQuery — Neighboring Selectors

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.

.next()

The .next() method get the element sibling element that immediately follows a given element.

For example, if we have:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li class="third-item">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Then we get the li that’s immediately next to the li with class third-item by writing:

$("li.third-item").next().css("background-color", "red");

Then we call css to add a red background color to it.

Next Adjacent Selector (“prev + next”)

We can use the next adjacent selector to add the adjacent selector to get the sibling element next to the given element.

For example, if we have:

<form>
  <label for="name">Name:</label>
  <input name="name" id="name">
  <fieldset>
    <label for="newsletter">Newsletter:</label>
    <input name="newsletter" id="newsletter">
  </fieldset>
</form>
<input name="none">

Then we can get the input next to the label and add some styles and set their value by writing:

$("label + input").css("color", "blue").val("Labeled!");

Next Siblings Selector (“prev ~ siblings”)

The next sibling selector lets us select all sibling elements that follow the prev element.

The siblings must have the same parent.

For example, if we have:

<div>div (doesn't match since before #prev)</div>
<span id="prev">span#prev</span>
<div>div sibling</div>
<div>div sibling <div id="small">div niece</div>
</div>
<span>span sibling (not div)</span>
<div>div sibling</div>

Then we can get all the divs that comes with the span with ID prev by writing:

$("#prev ~ div").css("border", "3px groove blue");

We call css to add a blue border to the matching elements.

.nextAll()

The .nextAll() method gets all the following siblings of each element in the set of matched elements.

For example, if we have:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li class="third-item">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Then we get all the li s that comes after the li with the class third-item and add a red background to them by writing:

$("li.third-item").nextAll().css("background-color", "red");

.nextUntil()

The .nextUntil() method gets all the following siblings of each element up to but not including the element matched by a selector, DOM node, or jQuery object passed in.

For example, if we have:

<dl>
  <dt id="term-1">term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>
  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>
  <dt id="term-3">term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>

Then we get the dt element with ID term-2 up to the dt with ID term-3 by writing:

$("#term-2")
  .nextUntil("dt")
  .css("background-color", "red");

Then we add a red background to it.

.not()

We call not to remove elements from a set of matched elements.

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 get all the li s in odd-numbered positions by writing:

$("li").not(":nth-child(2n)").css("background-color", "red");

Then we call css to add a red background to it.

Conclusion

We can get elements at various positions with jQuery.

Categories
jQuery

jQuery — Mouse Events and Multiple Selections

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.

.mousemove()

The .mousemove() method lets us add an event listener for the mousemove event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

.mouseout()

The .mouseout() method lets us add an event listener for the mouseout event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

.mouseover()

The .mouseover() method lets us add an event listener for the mouseover event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

.mouseup()

The .mouseup() method lets us add an event listener for the mouseup event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mouseup event on the div with ID target when we click on the div with ID other by writing:

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

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

Multiple Attribute Selector [name=”value”][name2=”value2″]

We can select items with multiple attributes with the multiple attribute selector.

For example, if we have:

<input id="man-news" name="man-news">
<input name="milkman">
<input id="letterman" name="new-letterman">
<input name="newmilk">

Then we can get the input with ID letterman and name value new-letterman by writing:

$("input[id][name$='man']").val("only this one");

After we got the element, we call val to set the input value.

Multiple Selector (“selector1, selector2, selectorN”)

The multiple selector selector lets us get elements that match any of the given selectors.

For example, if we have:

<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>

Then we can add a red border to the div , span , and the p element with class myClass by writing:

$("div, span, p.myClass").css("border", "3px solid red");

Conclusion

We can listen and trigger to mouse events and select elements with jQuery.

Categories
jQuery

jQuery — Mouse Events and Element Count

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.

.length

We can get the number of elements in the jQuery object with the .length property.

For example, if we have:

<div></div>

Then we add a div and get the total number of divs by writing:

$(document.body).append($("<div>"));
const n = $("div").length;
console.log(n);

The console log should log 2.

.load()

The .load() method lets us load data from the server and place the returned HTML into matched elements.

For example, if we have:

<div id='result'></div>

Then we can write:

$("#result").load("https://jsfiddle.net");

to load the content of https://jsfiddle.net into the div with ID result .

.map()

The .map() method lets us map the values of each item into a new value.

For example, if we have:

<form method="post" action="">
  <fieldset>
    <div>
      <label for="two">2</label>
      <input type="checkbox" value="2" id="two" name="number[]">
    </div>
    <div>
      <label for="four">4</label>
      <input type="checkbox" value="4" id="four" name="number[]">
    </div>
    <div>
      <label for="six">6</label>
      <input type="checkbox" value="6" id="six" name="number[]">
    </div>
    <div>
      <label for="eight">8</label>
      <input type="checkbox" value="8" id="eight" name="number[]">
    </div>
  </fieldset>
</form>

Then we get all the checkboxes’ IDs and then join them into a string by writing:

const str = $(":checkbox")
  .map(function() {
    return this.id;
  })
  .get()
  .join();
console.log(str);

Then str is ‘two,four,six,eight’ .

.mousedown()

The .mousedown() method lets us add an event listener to the mousedown event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

.mouseenter()

The .mouseenter() method lets us add an event listener for the mousedown event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

.mouseleave()

The .mouseleave() method lets us add an event listener for the mouseleave event or trigger it.

For example, if we have:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the mouswdown event on the div with ID target by writing:

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

Also, we can trigger then mousedown event on the div with ID target when we click on the div with ID other by writing:

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

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

Conclusion

We can listen or trigger to mouse events with jQuery.

Categories
jQuery

jQuery — Thenables and Keydown

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.

jQuery.ready

The jQuery.ready is a thenable object that resolves when the document is ready.

For example, we can write:

(async () => {
  const data = await $.when(
    $.getJSON("https://jsonplaceholder.typicode.com/posts/1"),
    $.ready
  )
  console.log(data);
})()

We call getJSON to get JSON data.

Then we call $.ready to wait for the document to be ready.

Then we get the data after both operations are done.

jQuery.readyException()

The jQuery.readyException method handles errors that are thrown synchronously in functions wrapped in jQuery.

For example, we can write:

jQuery.readyException = function(error) {
  console.error(error);
};

to pass the error object into the console.error method and log it.

jQuery.removeData()

The jQuery.removeData() method lets us remove data from an element.

For example, if we have:

<div></div>

Then we can use removeData to remove data from the div:

const div = $("div")[0];
jQuery.data(div, "test1", "value");
console.log(jQuery.data(div, "test1"))
jQuery.removeData(div, "test1");
console.log(jQuery.data(div, "test1"))

We get the div and then call jQuery.data to get the data.

Then we call removeData to remove the data.

So the first console log logs ‘value’ and the 2nd one logs undefined .

jQuery.support

The jQuery.support property has an object that shows what browser features are supported.

jQuery.uniqueSort()

The jQuery.uniqueSort() method sorts an array of DOM elements in place with the duplicates removed.

For example, if we have:

<div></div>
<div class="dup"></div>
<div class="dup"></div>
<div class="dup"></div>
<div></div>

Then we can use it as follows:

let divs = $("div").get();
divs = divs.concat($(".dup").get());
console.log(divs.length)
divs = jQuery.uniqueSort(divs);
console.log(divs.length)

We get the divs. Then we add the divs with class dup into the divs element list.

Then we call uniqueSort to sort them and remove the duplicates.

Therefore, the first console log logs 8 and the 2nd one logs 5.

jQuery.when()

We can use the jQuery.when() method to run callback functions based on 0 or more thenable objects.

For example, we can write:

(async () => {
  const data = await $.when($.ajax("https://jsonplaceholder.typicode.com/posts"))
  console.log(data);
})()

to make a GET request and then log the data.

.keydown()

The .keydown() method lets us listen to the keydown event on an element.

For example, if we have:

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

Then we can use it to listen to the keydown events on the input element by writing:

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

We can also use it to trigger a keydown event on another element.

For example, if we have the same HTML, then we can write:

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

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

to trigger the keydown event on the input when we click on the div with ID other .

Conclusion

We can run thenable code and then wait for the result with jQuery.

Also, we can listen or trigger keydown events.