One element, multiple events |
One element, multiple events |
RainLover |
Jun 18 2014, 09:50 PM
Post
#1
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
In jQuery you can easily do it like this:
CODE $("#foo").focus(function () { // Do this. }).blur(function () { // Do that. }); Can we do something similar in JavaScript so we don't have to repeat #foo in two separate functions? This post has been edited by RainLover: Jun 18 2014, 09:51 PM |
Christian J |
Jun 19 2014, 06:42 AM
Post
#2
|
. Group: WDG Moderators Posts: 9,653 Joined: 10-August 06 Member No.: 7 |
Is this the same question as http://forums.htmlhelp.com/index.php?showtopic=20126 ?
|
Christian J |
Jun 19 2014, 06:53 AM
Post
#3
|
. Group: WDG Moderators Posts: 9,653 Joined: 10-August 06 Member No.: 7 |
The following appears to work, but I don't know if it's good coding practice (or how nesting affects the this keyword):
CODE element.onmouseover=function() { this.style.background='red'; this.onmouseout=function() { this.style.background='pink'; } this.onclick=function() { this.style.color='lime'; this.onmouseout=function() { this.style.background='blue'; } } } Note the two mouseout events: which one that fires depends on if you have clicked or not. |
RainLover |
Jun 20 2014, 01:13 AM
Post
#4
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
Not really: my previous thread was about two events on the same element and with the same function. Later I learned how to do it: CODE element.oninput = element.onchange = doThis; But this thread is to do with two events on the same element with two functions. This post has been edited by RainLover: Jun 20 2014, 01:15 AM |
RainLover |
Jun 20 2014, 01:17 AM
Post
#5
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
The following appears to work, but I don't know if it's good coding practice (or how nesting affects the this keyword): CODE element.onmouseover=function() { this.style.background='red'; this.onmouseout=function() { this.style.background='pink'; } this.onclick=function() { this.style.color='lime'; this.onmouseout=function() { this.style.background='blue'; } } } Note the two mouseout events: which one that fires depends on if you have clicked or not. It seems to be easier to use two separate functions for #foo. Thanks for the suggestion, anyway! This post has been edited by RainLover: Jun 20 2014, 01:36 AM |
Lo-Fi Version | Time is now: 19th April 2024 - 02:28 PM |