Cecil Theodore
Cecil Theodore

Reputation: 9939

Kill function after click event JavaScript

I have a function that I want to be stopped when I run a 'close' click event.

The reasoning behind this is when I run img.start click event for the second time, the function is called again and is now running twice.

The function in question is a slideshow, so I really do need the function to only ever be running once on a page.

So just to be clear, when I click on img.close, I want the BannerSlideshow function to stop and not be running anymore.

Start function click event

$('img.start').click(function () {
  BannerSlideshow.Init()
});

End function click event

$('img.close').click(function () {
  //stop function BannerSlideshow from running
});

Snippet of slideshow function

var BannerSlideshow = (function () {
return {
    Init: function () {
        //slideshow functionality            
    }

I have updated my question to be more specific, apologies guys.

Upvotes: 1

Views: 13699

Answers (5)

Miklos Aubert
Miklos Aubert

Reputation: 4565

What does the StartSlideshow function look like? I guess you could have a global variable to run the slideshow or not...

function StartSlideshow() {
    globalVariableRunSlideshow = true;
    while (globalVariableRunSlideshow) {
         /* Do some slideshowing here */
    }
}

And then your event could do something like :

$('img.close').click(function () {
    globalVariableRunSlideshow = false;
});

Upvotes: 0

mlwacosmos
mlwacosmos

Reputation: 4541

Why dont you use stop function with a boolean ?

var running = false;

$('img.close').click(function () {
    running = true;

});

if running = true, use stop() function otherwise start slide

I think stop function is better than to unbind handlers

Upvotes: 0

EnterJQ
EnterJQ

Reputation: 1014

you can do that by using bind () and unbind ()

$('img.close').bind('click',function () {
         // your code
    $(this).unbind('click');
});

OR

You can use Off()

$(this).off('click');

Upvotes: 1

Ravi Gadag
Ravi Gadag

Reputation: 15851

you can use off method. Off()

(As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements

$('img.close').off('click');

Upvotes: 0

Amrendra
Amrendra

Reputation: 2077

use this:

event.stopPropagation(); 

or use on.click

and kill using

$(this).off();

or

use .bind and  .unbind();

better see here :http://api.jquery.com/category/events/event-handler-attachment/

Upvotes: 0

Related Questions