0

so I have a very simple code

    $("#toggle_google").trigger("click");
    $("#toggle_google").click();
    
    $("[id^='toggle_']").on("click", function() {
    	console.log("clicked: " + $(this).attr("id").replace("toggle_", "").toString());
                    
      return false;
    });
    
    $("#toggle_google").on("click", function() {
    	console.log("clicked toggle_google");
        
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
      <a href="www.google.com" id="toggle_google">Google</a>
      <br>
      <a href="javascript:void(0)" id="toggle_bing">Bing</a>
    </p>

I don't get anything on my console when the page loads. If I click on the links, I get messages on my console.

I've come up with my code after reading various discussions in stackoverflow and also reading jquery.com

Any ideas why it isn't working?

Here's a jsfiddle link

1
  • 2
    You are triggering the click before you have added the onclick event listener. Commented Feb 23, 2018 at 6:19

1 Answer 1

1

You have defined your click event after calling , so just revers it. and it will work fine.

$("[id^='toggle_']").on("click", function() {
    console.log("clicked: " + $(this).attr("id").replace("toggle_", "").toString());

});

$("#toggle_google").on("click", function() {
    console.log("clicked google");
});

$("#toggle_google").trigger("click");
$("#toggle_google").click();

LiNK

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.