Calling an event from a javascript plugin

Hi sitepointers I hope you are all well :slight_smile:

i am attempting an interactive javascript quiz using Yes or No answers, I found this very useful plugin

http://olance.github.io/jQuery-switchButton/

On one of my questions I need to fire an event in that it checks if the tick has been ticked and shows the hidden question, so I thought I could do it like this

	 $('.switch-button-button').click(function(){
		if($('.question-slider input').is(':checked')){
		alert("Test");
		}
	 });

But nothing happens, if I write this inside the plugin’s js file it fires

            this.button.click(function(e) {
                e.preventDefault();
                e.stopPropagation();
                self._toggleSwitch();
		if($('.question-slider input').is(':checked')){
		alert("Test");
		}
                return false;
            });

Why dosen’t it fire in my main js file, but the event fires in the plugin’s script file.

Thanks again,

harshy

Hi there,

I would imagine that the e.stopPropogation() call prevents the event from bubbling up and thus it never reaches the click handler you attach.

If you could post a link to a page where I could see this, I don’t mind having a look for you.

Thanks Pullo,

I’ll put it up in a hidden place, thanks again,

harshy

Hi there,

I got your PM and clicked on “Technology”, but what then?
I can’t see any tick to tick.
Could you be a bit more exact as to how I can reproduce your issue?

Hello Pullo

Thanks for your reply, yes I forgot to say in my panic you click on technology, then click e-learning and in there there are a series of questions which use the yes no slider, as soon as you click no it should fire the event but it isnt :frowning:

So, I had a look at this and it seems that the event id being stopped from bubbling in this function:

this.button_bg.click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  self._toggleSwitch();
  return false;
});

Also, the element you are trying to attach the handler to is not present when the DOM is rendered, so even if you could overcome the above problem, what you are trying will not work.
You will have to use event delegation:

$("body").on("click", "question-slider input", function(){
  if($(this).is(':checked')){
    alert("Test");
});

Hope that helps.

Hello Pullo

Many thanks for your reply I put your code


	$("body").on("click", ".switch-button-button", function(){
	  if($(this).is(':checked')){
		alert("Test");
	}
	});

after the document ready but its still the same it didnt fire the alert, what have I done wrong?

Hey,

You’re not doing anything wrong.
The function that starts this.button_bg.click(function(e) { ... } is stopping the click event bubbling up through the DOM, so that it doesn’t reach your click handler.

I don’t think that there’s a lot you can do about that I’m afraid (although I’d be interested to be proven wrong), other than modify the plugin as you were previously doing.