Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only call function once?

Tags:

javascript

So I have this javascript on a project I'm working on:

<script type="text/javascript">

    document.getElementById('contact').onmouseover = function () 
    {
        var w = 130;
        function step() 
        {
            if (w < 250) 
            {
                middle.style.width = (w++) + "px";
                setTimeout(step, 5);
            }
        }
        setTimeout(step, 1500); 
    };

</script>

I want this to run only once. After it detects a mouseover, I want it to run the function and then never run again until the page refreshes. How would I accomplish this?

like image 610
Bill Avatar asked Jun 28 '26 05:06

Bill


1 Answers

I'd either use jQuery's one method or if you want to use 'plain' JavaScript you could just remove the event after the function has been triggered. Here's an example:

// Create a named function for the mouseover event
function myFunc() {
    // Remove the `myFunc` function event listener once `myFunc` is run
    document.getElementById('contact').removeEventListener('mouseover', myFunc, false);

    var w = 130;
    function step() {
        if (w < 250) {
            middle.style.width = (w++) + "px";
            setTimeout(step, 5);
        }
    }
    setTimeout(step, 1500);
};

// Add an event listener to run the `myFunc` function on mouseover
document.getElementById('contact').addEventListener('mouseover', myFunc, false);

Note that if you have to support IE8 (or even earlier), you need to use ...attachEvent("onmouseover", myFunc) and detachEvent("onmouseover", myFunc); instead; you can tell by checking if the element has addEventListener:

var elm = document.getElementById('contact')
if (elm.addEventListener) {
    // Use addEventListener
}
else {
    // Use attachEvent
}

(Perhaps hidden away in a utility function.)

like image 76
pseudosavant Avatar answered Jun 29 '26 17:06

pseudosavant