Q:

How to Trigger a Click on a Link Using jQuery

0

How to Trigger a Click on a Link Using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery click() Method

You can use the click() method to trigger a click on a link programmatically using jQuery.

In the following example clicking the button will create the same effect as clicking the anchor or link manually using mouse. Let's try it out and see how it really works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Trigger Click on a Link</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function doSomething(){
    alert("Click event is triggered on the link.");
}
$(document).ready(function(){
    $("button").click(function(){
        $("a")[0].click();
    });
});
</script>
</head> 
<body>
    <p><a href="#skyImage" onclick="doSomething()">Bookmark link to an image</a></p>
    <button type="button">Trigger Click</button>
    <div style="margin-top: 800px;">
        <img src="/examples/images/sky.jpg" id="skyImage" alt="Cloudy Sky">
    </div>
</body>
</html>

However, if you simply want to execute the click event handler attached to the hyperlink, you can just use the jQuery trigger() method. For instance, in the above example, if you replace the statement at line no-13 with $("a").trigger("click"); then clicking the button will execute the doSomething() function and show the alert, but won't show the bookmarked image.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Class of the Clicked Element in jQu... >>
<< How to Load Local JSON File Using jQuery...