Rich Episcopo
Rich Episcopo

Reputation: 599

Can I add onmouseover attribute to run only once?

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
});

Upvotes: 6

Views: 4960

Answers (4)

Roberto Fernandes
Roberto Fernandes

Reputation: 94

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?

Upvotes: 1

An0nC0d3r
An0nC0d3r

Reputation: 1303

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 
     }

});

Upvotes: -1

Harsh Makani
Harsh Makani

Reputation: 761

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;
    }
});

Upvotes: -2

taxicala
taxicala

Reputation: 21769

You can nullify the onmouseover binding afterwards:

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

Upvotes: 11

Related Questions