How to use jQuery in a Page or Post

jQuery is a great JavaScript library with an easy to use selector. For instance if you write $(‘p’) in the script all <p> elements are selected. Then you can manipulate and animate them. In this article you will learn how to use jQuery on a page or post in WordPress.

In order to use jQuery you must get the library. Here we’ll use a CDN. You can import the jQuery CDN in a custom HTML block, like this:

<script
  src="https://code.jquery.com/jquery-3.6.3.min.js"
  integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
  crossorigin="anonymous"></script>

That’s it. Now you can use jQuery.

Just for the Hell of it, let’s try and create a button that will hide/show all <p> tags. Select the button, and give it an id. You can do this in advanced settings. Here the id is removeP.

Here is the code that should remove the <p>-elements. Add the script tag to a custom HTML block:

<script>
$('#removeP').click(function(){
   $('p').toggle(777);
})
</script>

The code above will detect a click event on the button. We gave the button the id removeP. When a click is detected a new selector will mark all <p> elements and toggle them. A toggle is a bit like a normal on/off switch on the wall. If the elements are visible they will hide away. Or vice versa. The number in the parethesis (777) is the number of microseconds that the toggle animation will last.

Now try to click the button. Does it work as intended?


Posted

in

, , ,

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enable Notifications OK No thanks

We use cookies - more information

Multimusen.dk will set a few cookies from Doubleclick, Google and the Social Media plugins they ay set some cookies. Some of my pages use APIs - such as YouTube, LinkedIn, Google Fonts, Google Maps, Mapbox, Spotify, Jetpack, Twitter, Facebook &c.. Such plugins may set the odd cookie.

Close