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.

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.