Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Basic Operations

Vanilla JavaScript in the browser now has many of the features of jQuery built in,

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Selecting Elements

We can use the querySelector method to select a single element with the given selector in vanilla JavaScript.

Vanilla JavaScript also has the querySelectorAll method to select multiple elements with the given selector with vanilla JavaScript.

For instance, we can write:

document.querySelector("div");

to select the first div in the document.

And select all the divs with:

document.querySelectorAll("div");

querySelectorAll returns a NodeList object, which is an iterable object with all the selected nodes inside.

In jQuery, we have:

$("div");

to select all the divs.

Run a Function on All Selected Elements

In jQuery, we can run a function on all selected elements.

For instance, we can hide all the divs by writing:

$("div").hide();

To do the same thing with vanilla JavaScript, we can use the forEach method:

document.querySelectorAll("div")
  .forEach(div => {
    div.style.display = "none"
  })

We can also use the for-of loop:

for (const div of document.querySelectorAll("div")) {
  div.style.display = "none"
}

The NodeList returned by querySelector can also be spread:

const divs = [...document.querySelectorAll("div")]
divs
  .forEach(div => {
    div.style.display = "none"
  })

divs is now an array instead of a NodeList.

This means we can run many array methods on it.

Finding an Element within Another

To find an element within another with jQuery, we use the find method:

const div = $("div");
//...
div.find(".box");

To do the same thing with vanilla JavaScript, we can use querySelector to find one element and querySelectorAll to find all instances of the element with the given selector.

So we write:

const div = document.querySelector('div')
//...
div.querySelector(".box");

to find the first element with class box in the div.

And we write:

const div = document.querySelector('div')
//...
div.querySelectorAll(".box");

to find all elements with class box in the div.

Traversing the Tree with parent(), next(), and prev()

jQuery has the parent method to get the parent element of an element.

jQuery’s next method returns the next sibling element of an element.

And jQuery’s prev method returns the previous sibling element of an element.

To use them, we can write:

$("div").next();
$("div").prev();
$("div").parent();

In vanilla JavaScript, we can write:

const div = document.querySelector("div");
div.nextElementSibling;
div.previousElementSibling;
div.parentElement;

nextElementSibling returns the next sibling element.

previousElementSibling returns the previous sibling element.

And parentElement returns the parent element.

Working with Events

jQuery lets us add event handlers easily to an element.

For instance, we can write:

$("button").click((e) => {
  /* handle click event */
});
$("button").mouseenter((e) => {
  /* handle click event */
});
$(document).keyup((e) => {
  /* handle key up event */
});

to add a click event handler, mouseenter event handler, and keyup event handler on the element that’s selected respectively.

To do the same thing with vanilla JavaScript, we can use the addEventListener method:

document
  .querySelector("button")
  .addEventListener("click", (e) => {
    /* ... */
  });

document
  .querySelector("button")
  .addEventListener("mouseenter", (e) => {
    /* ... */
  });

document
  .addEventListener("keyup", (e) => {
    /* ... */
  });

We just select the element with querySelector and call addEventListener with the event name as the first argument and the event handler callback as the 2nd argument.

Conclusion

We can do many basic DOM operations like selecting elements, traversing the DOM tree, and adding event listeners to elements with vanilla JavaScript.

Categories
jQuery

jQuery — Key Events and Select Element by 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.

.keypress()

We can use the keypress method to listen to keypress events or trigger it.

For example, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keypress event on the input by writing:

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

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

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

.keyup()

The .keyup() method lets us listen to the keyup event or trigger it.

For instance, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keyup event on the input by writing:

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

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

$("#target").keyup(function() {
  console.log("Handler for .keypress() called.");
});$("#other").click(function() {
  $("#target").keyup();
});

:lang() Selector

The :lang selector lets us select all elements of the specified language.

For example, if we have the following HTML:

<div lang="en-us">red
  <div>white
    <div>and blue</div>
  </div>
</div>
<div lang="es-es">rojo
  <div>amarillo
    <div>y rojo</div>
  </div>
</div>

And CSS:

.spain {
  background-color: red;
  color: #ff0;
}.usa {
  background-color: red;
  color: #fff;
}

Then we can add the different classes to the div with different lang attribute values by writing:

$("div:lang(en-us)").addClass("usa");
$("div:lang(es-es)").addClass("spain");

.last()

We can get the last element in a set of matched elements with the .last method.

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 add a red background to the last li by writing:

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

We get the li's and then call last to get the last one.

:last-child Selector

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

For example, if we have the following HTML:

<div>
  <span>John,</span>
  <span>Karl,</span>
  <span>Brandon,</span>
  <span>Sam</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Ralph,</span>
  <span>David</span>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("div span:last-child")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

:last-of-type Selector

We can get the last element of a given type with the :last-pf-type selector.

For example, if we have the following HTML:

<div>
  <span>Corey,</span>
  <span>Yehuda,</span>
  <span>Adam,</span>
  <span>Todd</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Tim,</span>
  <b>Nobody</b>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("span:last-of-type")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

Conclusion

We can listen to key events and get elements by type with jQuery.

Categories
jQuery

jQuery — Deferred and Data

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.

.data()

We can store data within matched elements with the data method.

For example, we can write the following HTML:

<span></span>

Then use data to store and get the data as follows:

$("body").data("foo", 52);
$("span").first().text($("body").data("foo"));

We save the data with key 'foo' and value 52 in the first line.

Then in the 2nd line, we get the data and put it in the span .

.dblclick()

The .dblclick() method binds an event handler to the dblclick event or trigger the event on an element.

For example, if we have the following HTML:

<div id="target">
  Double-click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to double clicks on the div with ID target by writing:

$("#target").dblclick(function() {
  alert("Handler for .dblclick() called.");
});

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

$("#target").dblclick(function() {
  alert("Handler for .dblclick() called.");
});$("#other").click(function() {
  $("#target").dblclick();
});

deferred.always()

deferred.always() adds a callback to be called when the deferred object is resolved or rejected.

For example, we can write:

$.get("foo.php").always(function() {
  alert("$.get completed");
});

to call the alert when we make a GET request for foo.php .

deferred.catch()

The deferred.catch method adds a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("foo.php")
  .then(function() {
    alert("$.get succeeded");
  })
  .catch(function() {
    alert("$.get failed!");
  });

or:

(async () => {
  try {
    const res = await $.get("foo.php")
  } catch (error) {
    alert("$.get failed!");
  }
})()

$.get returns a thenable object so it works with async and await .

deferred.done()

The deferred.done() method lets us add a callback that’s called when the deferred object is resolved.

For example, we can write:

$.get("https://jsonplaceholder.typicode.com/todos/1")
  .done(function() {
    alert("$.get succeeded");
  });

to make a GET request https://jsonplaceholder.typicode.com/todos/1 and add run something after that.

deferred.fail()

The deferred.fail() method lets us add a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("test.php")
  .done(function() {
    alert("$.get succeeded");
  })
  .fail(function() {
    alert("$.get failed!");
  });

to add that.

deferred.pipe()

We can use the deferred.pipe() method to filter and chain deferred objects.

It returns another deferred object.

We can use it by writing:

const defer = $.Deferred(),
  filtered = defer.pipe(function(value) {
    return value * 2;
  });defer.resolve(5);
filtered.done(function(value) {
  alert(value);
});

We call defer.pipe with a callback that takes the resolved value from the defer object, multipole by it by 2, and return it in the callback.

Then we call defer.resolve(5) to pass 5 as the value of value in the pipe callback.

And we get the finalvalue in the done callback, which is 10.

We can chain deferred by writing:

const url = 'https://jsonplaceholder.typicode.com/posts/1';
const url2 = 'https://jsonplaceholder.typicode.com/posts/2';
const request = $.ajax(url, {
    dataType: "json"
  })
  .pipe(function(data) {
    console.log(data)
    return $.ajax(url2);
  })
  .done(function(data) {
    console.log(data)
  });

We call pipe on the first deferred object returned by $.ajax and then call done to get the data from the 2nd $.ajax call.

Conclusion

We can work with deferred objects with various jQuery methods.

Categories
jQuery

jQuery — Widths and Wrapping

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.

.width()

The .width() method gets the current computed width for the first element in the set of matched elements or set the width of every matched element.

For example, we can write:

console.log($(window).width());

to log the width of the window.

To set the widths of the divs given the following HTML:

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

And CSS:

div {  
  width: 70px;  
  height: 50px;  
  float: left;  
  margin: 5px;  
  background: red;  
  cursor: pointer;  
}

We can add click handlers to the divs and change the width inside by writing:

const modWidth = 50;  
$("div").one("click", function() {  
  $(this).width(modWidth)  
});

.wrap()

The .wrap() method lets us wrap an element with a wrapper element.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap each div with the class inner with a div with class new by writing:

$(".inner").wrap("<div class='new'></div>");

.wrapAll()

The .wrapAll() method lets us wrap an HTML structure around all elements 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 can wrap a div with class new around all the divs with class inner by writing:

$(".inner").wrapAll("<div class='new' />");

.wrapInner()

We can wrap an HTML structure around the content of each element in the set of matched elements with the wrapInner method.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap the content of each div with class inner with a div with class new by writing:

$(".inner").wrapInner("<div class='new'></div>");

Conclusion

We can wrap elements with other elements with jQuery.

Also, we can get and set the width of the elements.

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.