Categories
JavaScript Answers jQuery

How to Toggle Showing and Hiding a Div When Clicking a Button with jQuery?

To toggle showing and hiding a div when clicking a button with jQuery, we can use the jQuery toggle method to toggle a div on and off.

For instance, if we have the following HTML:

<input type='button' id='hideshow' value='hide/show'>  
<div id='content'>Hello World</div>

Then we toggle to show and hide a div when we click on the input button by writing:

$(document).ready(() => {  
  $('#hideshow').on('click', (event) => {  
    $('#content').toggle('show');  
  });  
});

We call $(‘#hideshow’).on with 'click' to add a click event handler for the button.

Then in the event handler, we call toggle with 'show' to toggle the div on and off.

Categories
JavaScript Answers jQuery

How to Add a Click Listener for Any Element in the Page Except on 1 Div with jQuery?

To add a click listener for any element in the page except on 1 div with jQuery, we can add a click event listener for the body and then check which element is clicked in the click event listener.

For instance, if we have:

<div id='menu-content'>  
  menu  
</div>  
<div>  
  foo  
</div>

Then we can add the click event listener to the body by writing:

$('body').click((evt) => {  
  if (evt.target.id === "menu-content") {  
    return  
  }  
  console.log('clicked')  
});

We call click with a callback that takes the evt event object.

Then we check if evt.target.id is 'menu-content' .

If it is, we stop running the function with the return statement.

Otherwise, we log 'clicked' .

Therefore, when we click on ‘foo’, we see 'clicked' logged.

Otherwise, we see nothing in the console log.

Conclusion

To add a click listener for any element in the page except on 1 div with jQuery, we can add a click event listener for the body and then check which element is clicked in the click event listener.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Creating and Appending Elements

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.

Creating Elements

We can use jQuery’s $ function to create elements.

For instance, we can write:

$("<div/>");
$("<span/>");

to create a div and span respectively.

To do the same thing with vanilla JavaScript, we use the document.createElement method:

document.createElement("div");
document.createElement("span");

To add some content to the created elements, we can set the textContent property to add text.

Or we can attach child nodes with the appendChild method.

To add text content, we write:

const element = document.createElement("div");
element.textContent = "text"

And to add child node, we can write:

const element = document.createElement("div");
const text = document.createTextNode("text");
element.appendChild(text);

Updating the DOM

In jQuery, we can use the text method to update the text content of an element.

For instance, we can write:

$("div").text("New text");

And to return the text content of the selected element, we can write:

$("div").text();

to call text with no argument.

To set the text content of an element with vanilla JavaScript, we can write:

document.querySelector("div").textContent = "New text";

And to get the text content of the selected element, we write:

document.querySelector("div").textContent

In jQuery to append a new child element, we use the append method:

$(".search-result").append($("<div/>"));

We append a new div to the element with class search-result .

To do the same thing with vanilla JavaScript, we call appendChild :

const element = document.createElement("div");
document.querySelector(".search-result").appendChild(element);

We create the div with createElement and pass the returned element into appendChild .

Conclusion

We can create text nodes and elements and attach it easily into the DOM with vanilla JavaScript.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Events and Style Manipulation

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.

Event Listening for Dynamically Added Elements

On many occasions, we want to listen to events on dynamically added elements.

In jQuery, we would use the on method to listen to the event on all the select elements.

For instance, we can write:

$("div").on("click", ".search-result", (e) => {
  //...
});

to listen to clicks on the elements with the search-result class in the div with the on method to attach the event listeners to them.

To do the same thing with vanilla JavaScript, we can use event delegation.

For instance, we can write:

document
  .querySelector('div')
  .addEventListener('click', (e) => {
    if (e.target.className === 'search-result') {
      //...
    }
  })

to call addEventListener on the div.

And then in the click event handler, we use e.target.className to get the class name of the element that we clicked on.

Then we compare that to see if we clicked on anything with the class search-result .

Triggering and Creating Events

In jQuery, we can use the trigger method to trigger an event.

For instance, we can write:

$(document).trigger("myEvent");
$("div").trigger("myEvent");

To do the same thing with vanilla JavaScript, we write:

document.dispatchEvent(new Event("myEvent"));
document.querySelector("div").dispatchEvent(new Event("myEvent"));

Wd call dispatchEvent on the selected element to trigger our one event.

Styling Elements

jQuery has the css method to let us style elements.

For instance, we can write:

$("div").css("color", "#000");

To do the same thing with vanilla JavaScript, we can write:

document.querySelector("div")
  .style.color = "#000";

We set the style.color property to set the CSS color property of the selected div.

We can also pass in an object into jQuery’s css method:

$("div").css({
  "color": "#000",
  "background-color": "red"
});

To do the same thing with vanilla JavaScript, we just set the properties of the style object property to the values we want:

const div = document.querySelector("div");
div.style.color = "#000";
div.style.backgroundColor = "red";

We can also set the style.cssText property to set multiple styles:

const div = document.querySelector("div");
div.style.cssText = "color: #000; background-color: red";

hide() and show()

jQuery comes with the hide method to let us hide the selected elements.

And we can use jQuery’s show method to show the selected elements.

For instance, we can write:

$("div").hide();
$("div").show();

to hide and show the div respectively.

To do the same thing with vanilla JavaScript, we can set the display CSS property to the value we want with JavaScript:

document.querySelector("div").style.display = "none";
document.querySelector("div").style.display = "block";

We hide the div by setting style.display to 'none' .

And we show the div by setting style.display to 'block' .

Conclusion

We can add event listeners and manipulate styles easily with vanilla browser JavaScript.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Wait for Document Load, Classes, and HTTP Requests

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.

Wait for Document to be Ready

With jQuery, we can use the $(document).ready callback to run code when the DOM is loaded:

$(document).ready(() => {  
  //...  
});

To do the same thing with vanilla JavaScript, we can listen to the DOMContentLoaded event on the document :

document.addEventListener("DOMContentLoaded", () => {  
  //...  
});

Working with Classes

jQuery has methods to let us add, remove or toggle classes of an element:

$("div").addClass("focus");  
$("div").removeClass("focus");  
$("div").toggleClass("focus");

addClass lets us add the focus class to the div.

removeClass lets us remove the focus class to the div.

toggleClass lets us toggle the focus class to the div.

To do the same thing with vanilla JavaScript, we can use the methods in the classList property of an element.

For instance, we can write:

const div = document.querySelector("div");  
div.classList.add("focus");  
div.classList.remove("focus");  
div.classList.toggle("focus");

classList.add adds the focus class.

classList.remove removes the focus class.

And classList.toggle toggles the focus class.

We can also add or remove multiple classes with:

const div = document.querySelector("div");  
div.classList.add("focus", "highlighted");  
div.classList.remove("focus", "highlighted");

classList.add adds the focus and highlighted classes.

classList.remove removes the focus and highlighted classes.

We can also use the classList.replace method to replace one class with another.

For instance, we can write:

document.querySelector("div").classList.replace("focus", "blurred");

The focus class is replaced with the blurred class with classList.replace .

Checking if an Element has a Class

jQuery comes with the hasClass method to check if an element has the given class.

For instance, we can write:

if ($("div").hasClass("focus")) {  
  //...  
}

To do the same thing with vanilla JavaScript, we can use the classList.contains method:

if (document.querySelector("div").classList.contains("focus")) {  
  //...  
}

Network Requests

jQuery comes with the get method to make GET requests.

It also comes with the ajax method to let us make any requests.

For instance, we can use ajax by writing:

$.ajax({  
  url: "https://yesno.wtf/api"  
}).done((data) => {  
  console.log(data)  
}).fail(() => {  
  // Handle error  
});

And we can use get by writing:

$.get({  
  url: "https://yesno.wtf/api"  
}).done((data) => {  
  console.log(data)  
}).fail(() => {  
  // Handle error  
});

With vanilla JavaScript, we can just use the fetch method:

(async () => {  
  try {  
    const res = await fetch('https://yesno.wtf/api')  
    const data = await res.json()  
    console.log(data)  
  } catch (error) {  
    console.log(error)  
  }  
})()

We call res.json to turn the JSON response data object into a JavaScript object.

fetch returns a promise which is more convenient than using done and fail callbacks.

Conclusion

We can use vanilla JavaScript to wait for the DOM to be ready, make HTTP requests, and manipulate element classes easily.