0

I have the following html:

<a class="expander" id="menMenu" onclick="expandMenu(this,event); return false;" href="" >Men</a>

When the page has loaded I want to read the URL and, if it contains the word 'men', I want the above link to be clicked.

Here's what I'm trying, console log works but the click doesn't happen:

window.onload = function() {
      var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
      var myWord = 'men';
      var a = new RegExp('\\b' + myWord + '\\b');
      var b = (a.test(newURL));
      if(b=true){
          console.log('true'); // this shows 'true' in console
          document.getElementById("menMenu").click();    
      }
  };
StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • Do you need to _literally_ register the click, or do you just want the menu to be expanded? – dan.john.daly Aug 14 '14 at 13:27
  • Just expanded, not literally a click – StudioTime Aug 14 '14 at 13:28
  • 1
    You can simply call the expandMenu function, unless you need to specifically call the click from that line for some reason, in which case you can do as this post says: http://stackoverflow.com/questions/906486/how-can-i-programmatically-invoke-an-onclick-event-from-a-anchor-tag-while-kee – ctwheels Aug 14 '14 at 13:29

1 Answers1

0

Just call the expandMenu function that the click would normally call.

For the parameters you need to reference the anchor object by simply passing it to the function via document.getElementById("menMenu"). Then for the event, you can create an event object and assign it's type, etc, and pass it to the function as well.

I'd also suggest changing your (b=true) into (b==true).

b=true will always return true since you are assigning b the value of true.

In the future if you really need to simulate a click, I suggest reading up on dispatching events. See this for reference: How to simulate a click with JavaScript?

Community
  • 1
  • 1