Enjoy an ad free experience by logging in. Not a member yet? Register.
|
|
Results 1 to 3 of 3
-
04-11-2016, 08:03 AM #1New Coder
- Join Date
- Dec 2011
- Posts
- 59
- Thanks
- 18
- Thanked 0 Times in 0 Posts
What is a click-handler and how to execute it from Javascript?
Assume I have a web page with the following (partial) code inside:
<i class="aaa bbb ccc">X</i>
When I (mouse) click on the "X" some javascript (?) click handler procedure is executed.
But which method excatly?
How do I call this click handler method from Javascript (without manual mouse click)?
PeterLast edited by pstein; 04-11-2016 at 01:01 PM.
-
04-11-2016, 06:47 PM #2Master Coder
- Join Date
- Jan 2011
- Location
- Washington
- Posts
- 6,251
- Thanks
- 30
- Thanked 859 Times in 857 Posts
The easiest way to do this is by using the thingy like this:
That should be <i class="aaa bbb ccc" who ha.Code:<i class="aaa bbb ccc" <script> function StopTheX(){ alert("Stop doing that!"); } </script>
But we have purists here that hate the onclick attribute and want us all to use an event listener. They don't like the alert either, but I do. And I personally don't like the <i> tag to do this in.
Lots of opinions and dislikes here.
To make things easy I inserted a ID, because classes implies a lot of them and we would need to search though them all to find out which element I was listening to was clicked.
Code:<i class="aaa bbb ccc" id="my_x">X</i> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> document.getElementById("my_x").addEventListener("click", function(){alert('Stop That, I say!')}); </script>Last edited by sunfighter; 04-11-2016 at 06:53 PM.
Evolution - The non-random survival of random variants.
Physics is actually atoms trying to understand themselves.
-
Users who have thanked sunfighter for this post:
pstein (04-16-2016)
-
04-12-2016, 11:18 PM #3Senior Coder
- Join Date
- Aug 2010
- Posts
- 1,103
- Thanks
- 30
- Thanked 241 Times in 239 Posts
you can only have one handler
you can have as many listemers as you like
<i class="aaa bbb ccc" >X</i>
<script>
my_x = document.getElementsByClassName("aaa")[0];
my_x.onclick=function(){alert('from handler')};//the one and only handler
my_x.addEventListener("click", function(){alert('from listener1')});
my_x.addEventListener("click", function(){alert('from listener2')});
my_x.onclick();//this will execute the handler only
my_x.click();//this will execute the handler and all listeners
</script>Last edited by DaveyErwin; 04-13-2016 at 01:01 AM.
Cleverness is serviceable for
everything,
sufficient in nothing.
-
Users who have thanked DaveyErwin for this post:
pstein (04-16-2016)



Reply With Quote
