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.

Categories
jQuery

jQuery — Show Animations

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.

.show()

The show displays the matched elements.

For example, if we have the following HTML:

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

And CSS:

img {
  display: none;
}

Then we can call the show method to show the image when we click on Click here by writing:

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

.siblings()

The siblings method lets us get the siblings of each element in the set of matched elements.

We can optionally pass in a selector into this method.

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 can get all the li s that are sibling of the one with the class third-item and add a background to it:

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

.slice()

The slice method lets us reduce a set of matched elements to a subset specified by the range of indexes.

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 the li starting with index 2 and up to and not including 4 by writing:

$("li").slice(2, 4).css("background-color", "red");

.slideDown()

The .slideDown() method displays the matched elements with a sliding motion.

For example, if we have the following HTML:

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

And CSS:

img {
  display: none;
}

Then we can get show the image with a slide down animation when we click on Click here by writing:

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

.slideToggle()

The .slideToggle() method lets us display or hide the matched elements with the sliding motion.

For example, if we have the following HTML:

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

And CSS:

img {
  display: none;
}

Then we can get toggle the image with a slide animation when we click on Click here by writing:

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

.slideUp()

The .slideUp() method hides the matched elements with a sliding motion.

For example, if we have the following HTML:

<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 get hide the image with a slide up animation when we click on Click here by writing:

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

.stop()

The stop method stops the currently running animation on the matched elements.

For example, if we have:

<div id="hoverme">
  Hover me
  <img id="hoverme" src="https://i.picsum.photos/id/23/200/200.jpg?hmac=IMR2f77CBqpauCb5W6kGzhwbKatX_r9IvgWj6n7FQ7c">
</div>

Then we can stop the animation on the matched element by writing:

$("#hoverme").hover(function() {
  $(this).find("img").stop(true, true).fadeOut();
}, function() {
  $(this).find("img").stop(true, true).fadeIn();
});

When we hover over the img with ID hover , then we fade out the image.

Otherwise, we fade in the image.

Conclusion

We can add various effects to our DOM elements with jQuery.

Categories
jQuery

jQuery — Scroll and Form Values

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.

.scrollTop()

The .scrollTop() method gets the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for each matched element.

For example, if we have:

<p>Hello</p>
<p></p>

Then we get the vertical positon of the scrollbar by writing:

const p = $("p").first();
$("p").last().text(p.scrollTop());

.select()

The .select() method binds to an event handler for the select JavaScript event.

We can also use it to trigger the 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>

We can watch for select events triggered on the input by writing:

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

Also, we can trigger select on the input when we click on the div with ID other by writing:

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

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

:selected Selector

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

For example, if we have:

<select name="garden" multiple="multiple">
  <option>Flowers</option>
  <option selected="selected">Shrubs</option>
  <option>Trees</option>
  <option selected="selected">Bushes</option>
  <option>Grass</option>
  <option>Dirt</option>
</select>
<div></div>

Then we can watch the select event on the select element by writing:

$("select")
  .change(function() {
    let str = "";
    $("select option:selected").each(function() {
      str += $(this).text();
    });
    $("div").text(str);
  })
  .trigger("change");

We get all the selected items in the change callback and put them all in the div.

.serialize()

We can use the .serialize() method to convert the form’s values into key-value pairs.

For example, if we have:

<form>
  <select name="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

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

  <br>
  <input type="checkbox" name="check" value="check1" id="ch1">
  <label for="ch1">check1</label>
  <input type="checkbox" name="check" value="check2" checked="checked" id="ch2">
  <label for="ch2">check2</label>

  <br>
  <input type="radio" name="radio" value="radio1" checked="checked" id="r1">
  <label for="r1">radio1</label>
  <input type="radio" name="radio" value="radio2" id="r2">
  <label for="r2">radio2</label>
</form>

Then we can log the values of the form whenever we change the value of the controls by writing:

const showValues = () => {
  const str = $("form").serialize();
  console.log(str);
}

$("input[type='checkbox'], input[type='radio']").on("click", showValues);
$("select").on("change", showValues);
showValues();

We watch for clicks and change events and call the showValues method whenever something is done to the form.

Then str is something like:

single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

.serializeArray()

We can call serializeArray to encode a set of form elements as an array of names and values.

For example, if we have:

<form>
  <div><input type="text" name="a" value="1" id="a"></div>
  <div><input type="text" name="b" value="2" id="b"></div>
  <div><input type="hidden" name="c" value="3" id="c"></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
      <option value="5" selected="selected">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
    </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f">
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g">
  </div>
</form>

Then we can serialize the form values to an array of objects by writing:

$("form").submit(function(event) {
  console.log($(this).serializeArray());
  event.preventDefault();
});

When we click Submit, we get something like:

[
  {
    "name": "a",
    "value": "1"
  },
  {
    "name": "b",
    "value": "2"
  },
  {
    "name": "c",
    "value": "3"
  },
  {
    "name": "d",
    "value": "4"
  },
  {
    "name": "e",
    "value": "5"
  }
]

logged.

Conclusion

We can watch for scroll position and serialize form values with jQuery.

Categories
jQuery

jQuery — Replacing Elements and Scrolling

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.

.replaceAll()

We call .replaceAll() to replace each target element with the set of matched elements.

For example, if we have:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

Then we can replace all the divs with class inner with an h2 element by writing:

$("<h2>New heading</h2>").replaceAll(".inner");

.replaceWith()

The .replaceWith() method lets us replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

For example, if we have:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

Then we can replace the div with the class second with an h2 by writing:

$("div.second").replaceWith("<h2>New heading</h2>");

:reset Selector

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

For example, if we have:

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

Then we get input with type reset and add a background and border to it by writing:

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

.resize()

The .resize() method lets us watch for resize JavaScript event or trigger it on an element.

For instance, we can use it by writing:

$(window).resize(function() {
  console.log("Handler for .resize() called.");
})

We log when window is resized.

:root Selector

The :root selector selects the element that’s the root of the element.

For example, we can use it by writing:

console.log($(":root")[0].nodeName)

Then we get 'HTML’ logged.

.scroll()

The .scroll() method binds an event handler to the scroll JavaScript event or lets us trigger it.

For example, if we have:

<div id="target" style="overflow: scroll; width: 200px; height: 100px;">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna
  aliqua. Ut enim ad minim veniam, quis nostrud exercitation
  ullamco laboris nisi ut aliquip ex ea commodo consequat.
  Duis aute irure dolor in reprehenderit in voluptate velit
  esse cillum dolore eu fugiat nulla pariatur. Excepteur
  sint occaecat cupidatat non proident, sunt in culpa qui
  officia deserunt mollit anim id est laborum.
</div>
<div id="other">
  Trigger the handler
</div>

Then we can watch for scrolling on the div with the ID target by writing:

$("#target").scroll(function() {
  console.log('scrolling');
});

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

$("#target").scroll(function() {
  console.log('scrolling');
});

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

.scrollLeft()

The .scrollLeft() method gets the current horizontal position of the scroll bar for the first element in the set of matched elements.

For example, if we have:

<p>Hello</p>
<p></p>

Then we get the horizontal positon of the scrollbar by writing:

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

Conclusion

We can replace elements and watch for scrolling with jQuery.