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.

Categories
jQuery

jQuery — Queues and Removing Items

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.

.queue()

The .queue() method shows the queue of functions to be executed on the matched elements.

For example, if we have:

<p>The queue length is: <span></span></p>
<div></div>

Then we can show the number of queued items by writing:

const div = $("div");

function runIt() {
  div
    .show("slow")
    .animate({
      left: "+=200"
    }, 2000)
    .slideToggle(1000)
    .slideToggle("fast")
    .animate({
      left: "-=200"
    }, 1500)
    .hide("slow")
    .show(1200)
    .slideUp("normal", runIt);
}

function showIt() {
  const n = div.queue("fx");
  $("span").text(n.length);
  setTimeout(showIt, 100);
}

runIt();
showIt();

The queue method with 'fx' gets the number of queued items for animations.

:radio Selector

The :radio selector lets us get radio button eleements.

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" name="asdf">
  <input type="radio" name="asdf">
  <input type="reset">
  <input type="submit">
  <input type="text">
  <select>
    <option>Option</option>
  </select>
  <textarea></textarea>
  <button>Button</button>
</form>

Then we can add a background and border to a radio button by writing:

$("form input:radio")
  .wrap("<span></span>")
  .parent()
  .css({
    background: "yellow",
    border: "3px red solid"
  });

.ready()

The ready method specifies a function to run when the DOM is fully loaded.

We can write:

$(document).ready(function() {
  // Handler for .ready() called.
});

or:

$(function() {
  // Handler for .ready() called.
});

We run code in the callback when document is loaded.

.remove()

The .remove() method lets us remove a set of matched elements in the DOM.

For example, if we have:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

Then we remove the div with the class hello by writing:

$(".hello").remove();

.removeAttr()

The .removeAttr() method removes an attribute from each element in the set of matched elements.

For example, if we have:

<input type="text" title="hello there">
<button>Change title</button>

Then we can toggle the title attribute on and off when we click the button by writing:

const inputTitle = $("input").attr("title");
$("button").click(function() {
  const input = $(this).next();
  if (input.attr("title") === inputTitle) {
    input.removeAttr("title")
  } else {
    input.attr("title", inputTitle);
  }
});

.removeClass()

We can call the .removeClass() method to remove one or more classes on an element.

For example, if we have:

<p class="blue under">Hello</p>

Then we can remove the blue and under classes by writing:

$("p").removeClass("blue under")

.removeData()

The .removeData() method to remove a previously-stored piece of data.

For example, if we have:

<div>hello</div>

Then we can add data to the div and remove it by writing:

$("div").data("test1", "value");
console.log($("div").data("test1"));
$("div").removeData("test1");
console.log($("div").data("test1"));

We call removeData to remove a piece of data by its key.

.removeProp()

We can use the removeProp propety for the set of matched elements.

For example, if we have:

<p></p>

Then we can add a property and remove it by writing:

const para = $("p");
para
  .prop("code", 1234)
  .append(String(para.prop("code")))
  .removeProp("code")
  .append(String(para.prop("code")));

The first argument is the property name.

And the 2nd argument is the value of it.

removeProp takes the name of the property we want to remove.

Conclusion

We can get queued items and remove classes and properties with jQuery.