Categories
jQuery

jQuery - Events and Fades

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.

event.stopPropagation()

We can call event.stopPropagation to stop event propagation to an element’s parent and ancestor selectors.

For example, if we have:

<p>paragraph</p>

We can write:

$("p").click(function(event) {
  event.stopPropagation();
  // Do something
});

to stop the click event’s propagation.

event.target

We can get the element that an event is triggered on with the event.target property.

For example, if we have:

<p>paragraph</p>

Then we can get which element is clicked in the body by writing:

$("body").click(function(event) {
  console.log("clicked: ", event.target.nodeName);
});

The nodeName gets the tag name of the element that’s clicked.

event.timeStamp

We can get when the event is triggered with the timestamp property.

For example, if we have:

<p>paragraph</p>

Then we can write:

$("body").click(function(event) {
  console.log(event.timeStamp);
});

Then when we click on the paragraph, we see the timestamp logged.

event.type

The event.type property lets us get the type of event that’s triggered.

For example, if we have:

<p>paragraph</p>

Then we can write:

$("p").click(function(event) {
  alert(event.type);
});

to get the type of event that’s triggered with event.type .

event.which

The event.which property lets us get the key on the keyboard or mouse that’s pressed.

For example, if we have:

<input id="whichkey" value="type something">

Then we can get the key code of the keyboard key that’s pressed by writing:

$("#whichkey").on("keydown", function(event) {
  console.log(event.type, event.which);
});

which returns a number that corresponds to the key.

.fadeIn()

The .fadeIn() method fades an item to opaque.

For example, if we have the following HTML:

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

and CSS:

#book {
  display: none;
}

We can make the photo appear slowly when we click on Click here by writing:

$("#clickme").click(function() {
  $("#fork").fadeIn("slow");
});

.fadeOut()

The .fadeOut() method lets us make an element disappear.

For example, if we have:

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

Then we can make the photo fade out when we click on Click here by writing:

$("#clickme").click(function() {
  $("#fork").fadeOut("slow");
});

.fadeTo()

The .fadeTo() method lets us set the opacity to fade to.

For example, we can write:

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

Then we can write:

$("#clickme").click(function() {
  $("#fork").fadeTo("slow", 0.5);
});

The 2nd argument is the opacity to fade to.

.fadeToggle()

The .fadeToggle() lets us display or hide the matched elements by animating their opacity.

For example, if we have:

<button>fadeToggle 1</button>
<button>fadeToggle 2</button>
<img id="fork" src="https://i.picsum.photos/id/23/200/200.jpg?hmac=IMR2f77CBqpauCb5W6kGzhwbKatX_r9IvgWj6n7FQ7c">

Then we can call the fadeToggle method by writing:

$("button").click(function() {
  $("#fork").first().fadeToggle("slow", "linear");
});

$("button").last().click(function() {
  $("#fork").first().fadeToggle("fast", "linear");
});

We add click listeners for the buttons so that we can call fadeToggle inside to toggle the fading when we click the buttons.

Conclusion

We can fade elements and manipulate events with jQuery.

Categories
jQuery

jQuery — Event Data and Propagation

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.

event.metaKey

We can check whether the meta key is pressed when an event is fired with the event.metaKey property.

In Windows, the meta key is the Windows key.

In macOS, the meta key is the command key.

For example, if we have:

<button value="Test" name="Test" id="checkMetaKey">Click me!</button>

Then we can check if the meta key is pressed when we click on the click me button by writing:

$("#checkMetaKey").click(function(event) {
  console.log(event.metaKey);
});

event.namespace

We can get the namespace of the event by using the event.namespace property.

For example, if we have:

<button>display event.namespace</button>
<p>

</p>

Then we can trigger an event with a namespace by writing:

$("p").on("test.something", function(event) {
  alert(event.namespace);
});
$("button").click(function(event) {
  $("p").trigger("test.something");
});

We trigger the test.something event on thr p element when we click on a button.

Then event.namespace should be something and that’s displayed in the alert.

event.pageX and event.pageY

We can get the x and y-coordinates of the mouse position relative to the left edge of the document with the event.pageX and event.pageY properties respectively.

For example, we can log the mouse coordinate as the mouse moves by writing HTML:

<div id="log"></div>

and JavaScript:

$(document).on("mousemove", function({
  pageX,
  pageY
}) {
  $("#log").text(`${pageX}, ${pageY}`);
});

We listen to the mousemove event and get the pageX and pageY properties from the event object.

event.preventDefault()

We call the event.preventDefault() method to prevent the default action from being run in our event.

For example, if we have:

<a href='https://google.com'>hello</a>Then

Then we can prevent users from going to https://google.com by writing:

$("a").click(function(event) {
  event.preventDefault();
});

event.relatedTarget

The event.relatedTarget property gets the other DOM elements involved in an event.

For example, if we have:

<div>
  <a href='https://google.com'>hello</a>
</div>

Then when we move the mouse of of the a element, we can get the element that the mouse moved to with this property:

$("a").mouseout(function(event) {
  alert(event.relatedTarget.nodeName);
});

We should see DIV in the alert since the mouse moved to the div.

event.result

The event.result property returns the last value returned by an event handler that’s triggered by the event.

For example, if we have:

<button>display event.result</button>

Then we can return a value in a click listener function and get its value with event.result :

$("button").click(function(event) {
  return "hello";
});
$("button").click(function(event) {
  console.log(event.result);
});

We return 'hello' in the first click listener.

Then we log event.result in the 2nd click listener.

It should log 'hello' since that’s the return value of the first click listener.

event.stopImmediatePropagation()

We can call the event.stopImmediatePropagation() method to stop event propagation.

For example, if we have the following HTML:

<p>paragraph</p>
<div>division</div>

and CSS:

p {
   height: 30px;
   width: 150px;
   background-color: #ccf;
}

div {
   height: 30px;
   width: 150px;
   background-color: #cfc;
}

Then we can call stopImmediatePropagation to stop the propagation of the click event trigger on the p by writing:

$("p").click(function(event) {
  event.stopImmediatePropagation();
});
$("p").click(function(event) {
  $(this).css("background-color", "#f00");
});
$("div").click(function(event) {
  $(this).css("background-color", "#f00");
});

event.stopImmediatePropagation() is called on the first click listener, so the 2nd one won’t run.

The div ‘s click listener isn’t affected.

Conclusion

We can check is the meta key is pressed, stop propagation of events, and get event data with jQuery.

Categories
jQuery

jQuery — Element Index and Event Object

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.

:eq() Selector

The :eq selector lets us select an element at the given index within the matched set.

For example, if we have:

<ul>  
  <li>item 1</li>  
  <li>item 2</li>  
  <li>item 3</li>  
  <li>item 4</li>  
  <li>item 5</li>  
</ul>

Then we can write:

$("li:eq(2)").css("background-color", "red");

to get the 3rd li and add a red background to it.

.even()

We can get the elements that are the ones with an even number index in the matched set with the even method.

For example, if we have:

<ul>  
  <li>item 1</li>  
  <li>item 2</li>  
  <li>item 3</li>  
  <li>item 4</li>  
  <li>item 5</li>  
</ul>

Then we call it by writing:

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

to add a red background to the li elements with an even index.

event.currentTarget

We can use the event.currentTarget property to get the current DOM element within the event bubbling phase.

For example, if we have:

<p>  
  click me  
</p>

We can get the p element that we clicked on by writing:

$("p").click(function(event) {  
  alert(event.currentTarget === this);  
});

The alert should be true since this is the p element that we clicked on, which is the same as event.currentTarget .

event.data

The event.data is a property with the data that as pass into an event.

For example, if we have the following HTML:

<button> 0 </button>  
<button> 1 </button>  
<button> 2 </button>  
<button> 3 </button>  
<button> 4 </button>

Then we can add click listeners to each element and get the data by writing:

for (let i = 0; i < 5; i++) {  
  $("button").eq(i).on("click", {  
    value: i  
  }, function(event) {  
    console.log('value: ', event.data.value)  
  });  
}

We get the event.data.value property’s value in the click callback.

This should be the same value as the value property we pass in as the 2nd argument.

event.delegateTarget

The event.delegateTarget property has the element where the currently called jQuery event handler was attached.

For example, if we have:

<div class='box'>  
  <button>  
    0  
  </button>  
</div>  
<div class='box'>  
  <button>  
    1  
  </button>  
</div>  
<div class='box'>  
  <button>  
    2  
  </button>  
</div>

Then we can set the div with the class box to have a red background when we click on the button inside by writing:

$(".box").on("click", "button", function(event) {  
  $(event.delegateTarget).css("background-color", "red");  
});

event.isDefaultPrevented()

We can call event.isDefaultPrevented() to check whether event.preventDefault() is called on an object.

For example, if we have:

<a>hello</a>

Then we can call this method by writing:

$("a").click(function(event) {  
  alert(event.isDefaultPrevented());   
  event.preventDefault();  
  alert(event.isDefaultPrevented());   
});

We call the method and show its return value in the alert box.

event.isPropagationStopped()

We can call the event.isPropagationStopped() method to check if we called event.stopPropagation() .

For example, if we have:

<button>click me</button>

Then we can call this method by writing:

$("button").click(function(event) {  
  alert(event.isPropagationStopped());  
  event.stopPropagation();  
  alert(event.isPropagationStopped());  
});

Conclusion

We can get matched items by its index.

Also, we can check if stopPropagation and preventDefault are called with jQuery methods.

Categories
jQuery

jQuery - Selecting 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.

:disabled Selector

We can get inputs that are disabled with the :disabled selector.

For example, if we have the following HTML:

<form>  
  <input name="email" disabled="disabled">  
  <input name="id">  
</form>

Then we can set the value of the disabled input by writing:

$("input:disabled").val("this is it");

.each()

The .each() method lets us iterate over a jQuery object.

For example, if we have the following HTML:

<ul>  
  <li>foo</li>  
  <li>bar</li>  
</ul>

Then we can get all the li elements by writing:

$("li").each(function(index) {  
  console.log(index, $(this).text());  
});

Element Selector

We can get elements with the given tag name with the element selector.

For example, if we have the following HTML:

<div>DIV1</div>  
<div>DIV2</div>  
<span>SPAN</span>

Then we can add a red border to all the divs by writing:

$("div").css("border", "9px solid red");

.empty()

The .empty() method removes all child nodes of the set of matched elements in the DOM.

For example, if we have the following HTML:

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

Then we can call empty by writing:

$(".hello").empty();

Now the div with class hello will no longer have the text inside it.

:empty Selector

We can use the :empty selector to get all elements that have no children.

For example, if we have:

<table>  
  <tr>  
    <td>TD #0</td>  
    <td></td>  
  </tr>  
  <tr>  
    <td>TD #2</td>  
    <td></td>  
  </tr>  
  <tr>  
    <td></td>  
    <td>TD#5</td>  
  </tr>  
</table>

Then we can add text to the empty td elements by writing:

$("td:empty")  
  .text("Was empty")  
  .css("background", "green");

We add the 'Was empty' text into the empty td element and add a green background to it.

:enabled Selector

We can use the :enabled selector to get all the enabled input elements.

For example, if we have the following HTML:

<form>  
  <input name="email" disabled>  
  <input name="id">  
</form>

Then we get the enabled input and set its value by writing:

$("input:enabled").val("this is it");

.end()

The .end method ends the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

For example, if we have the following HTML:

<ul class="first">  
  <li class="foo">list item 1</li>  
  <li>list item 2</li>  
  <li class="bar">list item 3</li>  
</ul>  
<ul class="second">  
  <li class="foo">list item 1</li>  
  <li>list item 2</li>  
  <li class="bar">list item 3</li>  
</ul>

We can apply styles on the li with class foo and the li with class bar in the same method chain by writing:

$("ul.first")  
  .find(".foo")  
  .css("background-color", "red")  
  .end()  
  .find(".bar")  
  .css("background-color", "green");

The end method lets us end working with li with class foo and then we call find to find another element.

.eq()

The .eq() method reduces a set of matched elements to the one with the given index.

For example, if we have:

<ul>  
  <li>item 1</li>  
  <li>item 2</li>  
  <li>item 3</li>  
  <li>item 4</li>  
  <li>item 5</li>  
</ul>

Then we can get the li with index 2, which is the 3rd one and add a red background to it by writing:

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

Conclusion

We can select elements and work with them with various methods.

Categories
jQuery

jQuery - Then, Dequeue, and Descendants

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.

deferred.then()

The deferred.then() lets us add handlers that are called when the deferred object is resolved, rejected, or still in progress.

For example, we can write:

$.get("https://jsonplaceholder.typicode.com/posts/1")
  .then(
    function() {
      alert("$.get succeeded");
    },
    function() {
      alert("$.get failed!");
    }
  );

We make a request with $.get , which returns a deferred object.

Then we call then with the success callback as the first argument and the failure callback as the 2nd argument.

.delay()

The .delay() method sets a timer to delay the execution of subsequent items in the queue.

For example, if we have the following HTML:

<div id="foo"></div>

and CSS:

#foo {
  width: 200px;
  height: 200px;
  min-height: 100px;
  background-color: green
}

We can add a slide up effect, then show the fade-in effect after a delay by writing:

$("#foo").slideUp(300).delay(800).fadeIn(400);

delay(800) adds a 800ms delay.

.dequeue()

The .dequeue() method runs the next function on the queue with the matched elements.

For example, if we have the following HTML:

<button>Start</button>
<div></div>

and CSS:

div {
   margin: 3px;
   width: 50px;
   position: absolute;
   height: 50px;
   left: 10px;
   top: 30px;
   background-color: yellow;
 }

div.red {
   background-color: red;
}

We can make the div slide around and turn red by writing:

$("button").click(function() {
  $("div")
    .animate({
      left: "+=200px"
    }, 2000)
    .animate({
      top: "0px"
    }, 600)
    .queue(function() {
      $(this).toggleClass("red").dequeue();
    })
    .animate({
      left: "10px",
      top: "30px"
    }, 700);
});

In the queue callback, we call:

$(this).toggleClass("red").dequeue();

to add the red class on the div.

Descendant Selector

We can select all elements that are descendants of a given selector.

For example, if we have the following HTML:

<form>
  <div>Form is surrounded by the green border.</div>
  <label for="name">Child of form:</label>
  <input name="name" id="name">

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

Then we can get the input elements in the form element by writing:

$("form input").css("border", "2px dotted blue");

.detach()

The .detach() remove the set of matched elements from the DOM.

For example, if we have the following HTML:

<p>Hello</p>
how are
<p>you?</p>
<button>Attach/detach paragraphs</button>

Then we can attach or detach the paragraphs when we click the button by writing:

let p;
$("button").click(function() {
  if (p) {
    p.appendTo("body");
    p = null;
  } else {
    p = $("p").detach();
  }
});

In the click handler, we check if there’s any p elements.

If there are any, then we call detach to remove them. The remove elements are returned by detach .

If there isn’t then we attach the p elements to the body and set p to null .

.die()

The die method removes event handlers previous attached using the live method.

For example, we can write:

$("p").die();

to unbind all event handlers bound to p elements.

We can also unbind only click event handlers by writing:

$("p").die('click');

Also, we can unbind a single event handler by writing:

const foo = function() {

};
$("p").live("click", foo);
$("p").die("click", foo);

We remove the foo click handler with the die method.

Conclusion

We can work with deferred objects with various methods.

Also, we can do various things with event handlers and descendant elements.