Categories
jQuery

jQuery — Previous Elements and Attributes

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.

.prev()

We call the .prev() method to get the immediately preceding sibling of each element in the set of matched elements.

If a selector is provided, it gets the precious siblings only if it matches that selector.

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 before the li with the class third-item by writing:

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

Then we add a red background to it.

.prevAll()

The .prevAll() method gets all preceding 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 preceding siblings of the li that has the class third-item and add a background to them by writing:

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

.prevUntil()

The .prevUntil() gets all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.

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 all the dd before the dt with ID term-2 and up to but not including the first dt by writing:

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

and we set their background to red.

.promise()

The .promise() method returns a promise to observe when all actions of a certain type bound to the collection have finished.

For instance, if we have:

<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>

Then we can show some text when we click on a button by writing:

$("button").on("click", function() {
  $("p").append("Started...");

  $("div").each(function(i) {
    $(this).fadeIn().fadeOut(1000 * (i + 1));
  });

  $("div").promise().done(function() {
    $("p").append(" Finished! ");
  });
});

We loop through each div and apply some fade effects with fadeIn and fadeOut .

Then we call promise and run code when all the method calls are done with the promise().done() method.

.prop()

We can use the prop method to get the attribute value.

For example, if we have:

<input id="check1" type="checkbox" checked="checked">

Then we can write:

$("input").change(function() {
  const $input = $(this);
  console.log($input.prop("checked"));
}).change();

to watch for the changes to the checkbox input.

We get the checked attribute’s value with the prop method.

.pushStack()

We call the pushStack method to add a collection of DOM elements onto the jQuery stack.

For example, if we have:

<div>
  foo
</div>

Then we call pushStack to add the div to the stack and remove it by writing:

jQuery([])
  .pushStack(document.getElementsByTagName("div"))
  .remove()
  .end();

Conclusion

We can get previous elements and get property values with jQuery.

Categories
jQuery

jQuery — Parent Elements

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.

.parents()

The .parents() method lets us get the ancestors of each element in the current set of matched elements.

We can optionally filter that with a selector.

For example, if we have:

<ul class="level-1">  
  <li class="item-i">I</li>  
  <li class="item-ii">II  
    <ul class="level-2">  
      <li class="item-a">A</li>  
      <li class="item-b">B  
        <ul class="level-3">  
          <li class="item-1">1</li>  
          <li class="item-2">2</li>  
          <li class="item-3">3</li>  
        </ul>  
      </li>  
      <li class="item-c">C</li>  
    </ul>  
  </li>  
  <li class="item-iii">III</li>  
</ul>

Then we get all the ancestors of the li with the item-a class by writing:

$("li.item-a").parents().css("background-color", "red");

Then we add a red background to it.

.parentsUntil()

The .parentsUntil() method gets the ancestors of each element in the current set of matched elements up to but nor including the element matched bu the selector, DOM node, or jQuery object.

For example, if we have:

<ul class="level-1 yes">  
  <li class="item-i">I</li>  
  <li class="item-ii">II  
    <ul class="level-2 yes">  
      <li class="item-a">A</li>  
      <li class="item-b">B  
        <ul class="level-3">  
          <li class="item-1">1</li>  
          <li class="item-2">2</li>  
          <li class="item-3">3</li>  
        </ul>  
      </li>  
      <li class="item-c">C</li>  
    </ul>  
  </li>  
  <li class="item-iii">III</li>  
</ul>

Then we can get the parents of the li with the item-a class up to but not including the li with class level-1 and add a background to them by writing:

$("li.item-a")  
  .parentsUntil(".level-1")  
  .css("background-color", "red");

:password Selector

The :password selector lets us select all elements with type password.

For example, if we have:

<form>  
  <input type="button" value="Input Button">  
  <input type="checkbox">  
  <input type="file">  
  <input type="hidden">  
  <input type="password">  
  <select>  
    <option>Option</option>  
  </select>  
  <textarea></textarea>  
  <button>Button</button>  
</form>

Then we write:

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

to add a yellow background and a red border to the input with type password.

.position()

The .position() method gets the current coordinates of the first element in the set of matched elements relative to the offset parent.

For example, if we have:

<p>Hello</p>

Then we can get the position of the p element by writing:

const p = $("p").first();  
const position = p.position();  
console.log(position)

And we get:

{top: 0, left: 8}

as the value of the position .

.prepend()

The .prepend() method inserts the content to the beginning of each element 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 add an element before the text node of each div with the class inner by writing:

$(".inner").prepend("<p>Test</p>");

.prependTo()

The .prependTo() method lets us prepend an element in a 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 prepend a p element to each div with the class inner as their child by writing:

$("<p>Test</p>").prependTo(".inner");

Conclusion

We can get parent elements and do many thing with them with jQuery.

Categories
jQuery

jQuery — Selecting Parents and Elements of One 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.

:only-of-type Selector

We can use the :only-of-type selector to select all elements that have no siblings with the same element name.

For example, if we have:

<div>
  <button>Sibling</button>
  <button>Sibling</button>
</div>

<div>
  <button>Sibling</button>
</div>

<div>
  None
</div>

<div>
  <button>Sibling</button>
  <button>Sibling</button>
  <button>Sibling</button>
</div>

<div>
  <button>Sibling</button>
</div>

Then we can get buttons that are the only child in the div by writing:

$("button:only-of-type").text("Alone").css("border", "2px blue solid");

Then we change their text and add a border to them.

.outerHeight()

The .outerHeight() method lets us get the computed outer height, which includes the padding, border, and optionally margin, for the first element in the set of matched elements.

It can also be used to set the outer height of every matched element.

For example, if we have:

<p>Hello</p>

Then we get the outer height with the margin by writing:

const p = $("p").first();
console.log(p.outerHeight(true));

true means we include the margin.

If we have:

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

Then we can set the outer height of the div when we click it by writing:

const modHeight = 60;
$("div").one("click", function() {
  $(this).outerHeight(modHeight);
});

.outerWidth()

The .outerWidth() method gets the current computed outer width, including the padding, border, and optionally the margin, for the first element of the set of matched elements.

It can also be used to set the outer width of all matched elements.

It can also be used to set the outer height of every matched element.

For example, if we have:

<p>Hello</p>

Then we get the outer height with the margin by writing:

const p = $("p").first();
console.log(p.outerWidth(true));

true means we include the margin.

If we have the following HTML:

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

and CSS:

.mod {
  background: blue;
  cursor: default;
}

Then we can set the outer height of the div when we click it by writing:

const modHeight = 60;
$("div").one("click", function() {
  $(this).outerWidth(modHeight).addClass("mod");;
});

We call addClass to add the mod class with a blue background.

.parent()

The .parent() method lets us get the parent element of the given element.

For example, if we have:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Then the li with the item-a class’s parent and add a background to it by writing:

$("li.item-a").parent().css("background-color", "red");

:parent Selector

The :parent selector lets us get the parent of a given element.

For example, if we have:

<table border="1">
  <tr>
    <td>Value 1</td>
    <td></td>
  </tr>
  <tr>
    <td>Value 2</td>
    <td></td>
  </tr>
</table>

Then we can fade the tr by writing:

$("td:parent").fadeTo(1500, 0.3);

Conclusion

We can select parent elements and elements with a given type with jQuery.

Categories
jQuery

jQuery — Offsets and Only Child

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.

.offset()

The .offset() method gets the current coordinates of the first element in the set of matched elements relative to the document.

For example, if we have:

<p>Hello</p>
<p>2nd Paragraph</p>

Then we can get the last p element’s offset by writing:

const p = $("p").last();
const offset = p.offset();
console.log(offset);

Then we get:

{
  "top": 50,
  "left": 8
}

as the value of offset .

.offsetParent()

The .offsetParent() method gets the closes ancestor element that’s positioned.

For example, if we have:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii" style="position: relative;">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Then we get the li with class item-a ‘s parent with the offsetParent method and add a background to it by writing:

$("li.item-a").offsetParent().css("background-color", "red");

.on()

The .on() method attaches an event handler function for one or more events to the selected elements.

For example, if we have:

<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>

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

$("p").on("myCustomEvent", function(event, myName) {
  $(this).text(`${myName}, hi there`);
  $("span")
    .stop()
    .css("opacity", 1)
    .text(`myName = ${myName}`)
    .fadeIn(30)
    .fadeOut(1000);
});

$("button").click(function() {
  $("p").trigger("myCustomEvent", ["John"]);
});

We call trigger with the event name as the first argument and the data we want to send with the event in an array.

To listen to the myCustomEvent event, we call on with the same event name as the first argument.

The 2nd argument is a callback that runs when the event is triggered.

myName is 'John' so we see that added to the p element.

.one()

The .one() method attaches a handler to an event for the elements.

The handler is run at most once per element per event type.

For example, if we have:

<p id='foo'>foo</p>

Then we write:

$("#foo").one("click mouseover", function(event) {
  alert("The " + event.type + " event happened!");
});

to add a listener for the click and mouseover events on the p element wiuth ID foowith the one method.

:only-child Selector

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

For example, if we have:

<div>
  <button>Sibling</button>
  <button>Sibling</button>
</div>

<div>
  <button>Sibling</button>
</div>

<div>
  None
</div>

<div>
  <button>Sibling</button>
  <button>Sibling</button>
  <button>Sibling</button>
</div>

<div>
  <button>Sibling</button>
</div>

Then we add a border and change the text of the buttons that are the only in the div by writing:

$("div button:only-child").text("Alone").css("border", "2px blue solid");

So the 2nd and last div will have the text changed and the border added.

Conclusion

We can add event listeners and get the only child element in an element with jQuery.

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.