jQuery Button Click Counter coding example and free lesson on jQuery

jQuery is a popular JavaScript library that makes it easy to manipulate HTML elements, handle events, and create animations. Here’s a common jQuery example that demonstrates how to select elements, add an event listener, and change the element’s text:

Copy code

<button id=”my-button”>Click me</button>

<p id=”my-text”>Hello</p>

<script>

    // Select the button and add a click event listener

    $(“#my-button”).click(function() {

        // Select the text element and change its text

        $(“#my-text”).text(“Button clicked!”);

    });

</script>

This code will create a button with the id “my-button” and a paragraph with the id “my-text”. When the button is clicked, the text of the paragraph will change to “Button clicked!”

First, we are using the $(“#my-button”) which is a jQuery selector that selects the element with the id “my-button” and this will return the button element as a jQuery object.

The .click(function(){…}) is a jQuery method that adds a click event listener to the button element. It takes a function as an argument, and this function will be executed when the button is clicked.

Inside the function, we are using the $(“#my-text”) selector again to select the paragraph element with id “my-text”. This will return the paragraph element as a jQuery object.

The .text(“Button clicked!”) is a jQuery method that changes the text of the selected element. In this case, it will change the text of the paragraph to “Button clicked!”.

So, in summary, this code is selecting the button element and adding a click event listener to it. When the button is clicked, it’s selecting the paragraph element and changing its text.

let counter = 0 ;

$(‘#my-btn’).click(function(){

counter++;

$(‘#my-text’).text(‘Click : ‘+counter);

console.log(counter);

})

Simple Click Counter

<!DOCTYPE html>

<html>

<head>

   <title>Learn jQuery</title>

</head>

<body>

   <h1>Learn JQuery Course </h1>

   <div class=”output”>

       <button id=”my-btn”>Click Me</button>

       <p id=”my-text”>Hello</p>

   </div>

   <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>

   <script src=”app8.js”></script>

</body>

</html>

let counter = 0 ;

$(‘#my-btn’).click(function(){

   counter++;

   $(‘#my-text’).text(‘Click : ‘+counter);

   console.log(counter);

})