jQuery programatically click a tag that has javascript:void(0)

2.5k views Asked by At

I am trying to programmatically click the "zoom in" icon three times on a page. The <a> is structured:

<a class="get-plus" title="zoom in" href="javascript:void(0)" style="display: inherit;">&nbsp;</a>

I have the following code, called on document ready:

function zoomIn() {
    // Zoom in 
    for (var i = 0; i < 3; i++) {
        $('a.get-plus').trigger('click');
        alert(i);
    }
}

I get the alerts that the loop works, but the zoom functionality isn't working, not sure how to fix or a better way to go about this?

2

There are 2 answers

5
gaetanoM On BEST ANSWER

Your way to trigger the click event doesn't work.

Instead use HTMLElement.click():

The HTMLElement.click() method simulates a mouse-click on an element.

When click() is used with supported elements (e.g. one of the types), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. One exception: The click() method will not cause an element to initiate navigation as if a real mouse-click had been received.

Therefore, change it from:

$('a.get-plus').trigger('click');

to:

$('a.get-plus').get(0).click();

The example:

function zoomInChanged() {
  // Zoom in
  for (var i = 0; i < 3; i++) {
    setTimeout(function () {
      $('a.get-plus').get(0).click();
    }, i * 1000);
  }
}

function zoomIn() {
  // Zoom in
  for (var i = 0; i < 3; i++) {
    $('a.get-plus').trigger('click');
    console.log(i);
  }
}

console.log('zoomIn:');
zoomIn();
console.log('zoomInChanged:');
zoomInChanged();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a class="get-plus" title="zoom in" href="javascript:console.log('Clicked')" style="display: inherit;">&nbsp;</a>

More reading:

jQuery's event handling system is a layer on top of native browser events. When an event handler is added using .on( "click", function() {...} ), it can be triggered using jQuery's .trigger( "click" ) because jQuery stores a reference to that handler when it is originally added.

Additionally, it will trigger the JavaScript inside the onclick attribute.

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.

2
Schlaus On

<a href="javascript:void(0)"> is a hack used to make something clickable, but not move the user to a new page. It is in no way related to your zoom functionality.

You're most likely using some sort of a library or plugin to make images zoomable. You should read the docs, and see if you library provides a way to programmatically trigger zooming.