3

Let's say i have a javascript function call function playGauge().

I want to call this function only once when either a div with class="myClass" is clicked or scrolled. For click I am using following code:

    var myclassClicked = false;
    $('.myClass').click(playGauge);


    function playGauge(){
    if (myclassClicked === true) return false;
    myclassClicked = true;
///do some other stuff
}

How to add scroll functionality in a similar way to my code and my function playGauge().

Thank you!

0

3 Answers 3

3

$.one is your friend:

$('.myClass').one('click scroll', function(event){ ... });
Sign up to request clarification or add additional context in comments.

6 Comments

That was my first thought as well, but it should be noted that this fires once for each element in the collection, and not just one time for all.
I haven't tested by I am under the impression that it will play once for every .myClass elements rather than once for all.
I'm not sure how it deals with multiple elements, but it fires once for each event type. so you get one for click and one for scroll: jsfiddle
@JohnS - you do, but as it's a class selector, there could be more than one element, and then the event handler would fire once for each element -> jsfiddle.net/Tx84F/1
@adeneo - I originally thought the OP wanted the event handler to run once per matching element, but perhaps I misinterpreted that.
|
3

Remove the event handler once the event occurs on any of the elements matching the selector

$('.myClass').on('click scroll', function() {
    $('.myClass').off('click scroll')
    playGauge();
});

5 Comments

Using event delegation would be slightly better.
@plalx - Why on earth would event delegation be better with non-dynamic elements? I don't get that comment at all!
Well, it all depends on how many .myClass elements there is on the page, but it will be more memory-efficient to register a single handler rather than multiple ones if there are many. Perhaps I should have said "using event delegation could be slightly better if there are many .myClass elements on the page."
@adeneo a comma was missing in the first line, but it only works for click and not for scroll.
That's strange, it works fine for me (added the comma btw!) -> jsfiddle.net/p8D5Y/1
0

Try to add event scroll :

$('.myClass').scroll(playGauge);

Documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.