ADVERTISEMENTS

How to define and call a function in jQuery

jQuery is a JavaScript library that makes it easy to manipulate HTML documents and interact with the Document Object Model (DOM). One of the core features of jQuery is its ability to select elements from the DOM and perform actions on them. We can write down a function for this action and call them on DOM element.

The following example will explain about simple jQuery function that selects all p elements on a page and changes their color to red when called. You can easily copy it and use with your own code.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Define and call a function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
    function changeColor() {
        $("p").css("color", "red");
    }
});
$("button").click(function(){
    changeColor();
});

</script> 
</head>
<body>
    <p>Demo text Here</p>
    <button type="button">Change Color</button>
</body>
</html>

 

Supported Browsers:
  • Internet Explorer
  • Mozilla Firefox
  • Google Chrome
  • Opera
  • Safari

jQuery is a javascript library language used to perform the action on DOM elements of HTML webpages. You can learn jquery from our Jquery Tutorials and Jquery Examples

ADVERTISEMENTS