Can I add onmouseover attribute to run only once?
Asked Answered
B

4

6

Say I have a link like the following:

<a class="link" href="www.rich.com" onmouseover="go(this)">Link</a>

Is there a way to configure the onmouseover event, calling go(this) to run only a single time while still using the inline onmouseover=<some code> notation? I want it defined inline, not with a JavaScript call.

Currently, I have this, but it is not what I want:

$(".link").one('mouseover', function(e) {
     // do something
});
Bohman answered 1/10, 2015 at 19:42 Comment(4)
You need to be a little more clear by what you mean only run once. Run once, literally. Run once per hover. Run once per .link ? Because .one should work.Quan
@Quan run once literally. Like using one().Bohman
Just curious - why do you prefer to do it this way?Foreigner
@SurrealDreams I want to do it this way because I rebuild links via AJAX calls and by doing it inline I don't have to have random function calls all over the code one the link is created and inserted into the DOM. Instead, I can "bind" an event handler when in only one place -- when I format the HTML string at the very beginning.Bohman
P
11

You can nullify the onmouseover binding afterwards:

<a class="link" href="www.rich.com" onmouseover="go(this); this.onmouseover = null;">Link</a>
Paulson answered 1/10, 2015 at 19:46 Comment(3)
Great answer. This is much cleaner then alternatives.Bohman
No problem. Glad to help!Paulson
How do I re-enable onmouseover when onmouseout?Babara
I
1

Using Vanilla JS:

const link = document.querySelector('.link');
link.addEventListener('mouseover',
  () = window.open('your url'),
  { once : true }
);

ref: How can I add an event for a one time click to a function?

Illlooking answered 16/5, 2022 at 16:46 Comment(0)
G
-1

You could set a var that indicates whether it has been triggered or not...

var triggered = false;

$(".link").one('mouseover', function(e) {
     // do something
     if(!triggered)
     {
        triggered = true;

        // and whatever else you want to do 
     }

});
Gigi answered 1/10, 2015 at 19:49 Comment(0)
C
-2

Alternatively you can do something like this :

var check = 0;
$(".link").on('mouseover', function(e) {
    if(check == 0 ){
       // do something
       check = 1;
    }else {
       return false;
    }
});
Chism answered 1/10, 2015 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.