Override jQuery on click handler function - javascript

I'm a newbie when it comes to jQuery and I'm hoping if there's a way to override an existing on click function.
The code is as follows:
$('.woo-star-rating').on('click', function() {
$('.woo-star-rating-filled').width( $(this).attr('data-rating') * 25 )
});
and I'd like to change the number 25 to 21 inside my own .js file.
$('.woo-star-rating').on('click', function() {
$('.woo-star-rating-filled').width( $(this).attr('data-rating') * 21 )
});

You can remove the existing click event handler using the .off() method add your new click event.
var $rating = $('.woo-star-rating');
$rating.off('click');
$rating.on('click', function() {
$('.woo-star-rating-filled').width( $(this).attr('data-rating') * 21 )
});
This can be chained into:
$('.woo-star-rating').off('click').on('click', function() {
$('.woo-star-rating-filled').width( $(this).attr('data-rating') * 21 )
});
Here's a working example:
// add junk event
$('#test-button').on('click', function() {
console.log('first button click');
});
// remove first event
$('#test-button').off('click');
// add new event, only this will fire on click
$('#test-button').on('click', function() {
console.log('second button click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test-button">Test Button</button>

Related

How do I stop .click()?

I create a button 2 button. "square" and "circle"
When I click square and click circle. Square could not stop working.
<button id="square">square</button>
<button id="circle">circle</button>
Do I need to do?
$('#square').on('click', function () { $("canvas").on({
mousedown: function (e) {
...
},
mousemove: function (e) {
..
},
mouseup: function () {
..
}
}); });
$('#circle').on('click', function () { $("canvas").on({
mousedown: function (e) {
...
},
mousemove: function (e) {
..
},
mouseup: function () {
..
}
}); });
If you add an event listener with jQuery method .on() you can remove this event listener with jQuery method .off() like this:
$('#square').on('click', fnEventHandler); // add ONE on click event listener to #square DOM element
$('#square').off('click'); // remove ALL on click event listeners from #square DOM element
For your specific mockup it could look somehow like this:
$('#square').on('click', function() {
console.log('button#square on click handler'); // just for debug purpose
$('#circle').off('click'); // remove button#circle event listener
// do what ever you want to do after click on #square eg: $("canvas").on(...)
});
$('#circle').on('click', function() {
console.log('button#circle on click handler'); // just for debug purpose
$('#square').off('click'); // remove button#square event listener
// do what ever you want to do after click on #circle eg: $("canvas").on(...)
});
Please click both buttons:
<button id="square">square</button>
<button id="circle">circle</button>
<br>
To reset the behavior click "Run code snippet" again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or you make use of the disabled-attribute:
$('#square').on('click', function() {
console.log('button#square on click handler'); // just for debug purpose
$('#circle').prop('disabled', true); // disable button#circle event listener
// do what ever you want to do after click on #square eg: $("canvas").on(...)
});
$('#circle').on('click', function() {
console.log('button#circle on click handler'); // just for debug purpose
$('#square').prop('disabled', true); // disable button#circle event listener
// do what ever you want to do after click on #circle eg: $("canvas").on(...)
});
Please click both buttons:
<button id="square">square</button>
<button id="circle">circle</button>
<br>
To reset the behavior click "Run code snippet" again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The snippets above should illustrate whats going on in essence.
The snippet below shows an advanced way to add, remove and re-add event listeners in a somehow more generic way.
(function( $ ) {
var oHasEventListener = {},
removeEventListener = function( sKey ) {
// sanitize sKey first
if ( !oOnClickHandler[ sKey ] ) {
return console.log('sKey: "' + sKey + '" is not available'); // just for debug purpose
}
if ( oHasEventListener[ sKey ] ) {
$('#' + sKey).off('click').prop('disabled', true);
oHasEventListener[ sKey ] = false;
console.log('button#' + sKey + ' on click listener removed'); // just for debug purpose
}
},
addEventListeners = function() {
for ( sKey in oOnClickHandler ) {
if ( !oHasEventListener[ sKey ] ) {
$('#' + sKey).on('click', oOnClickHandler[ sKey ]).prop('disabled', false);
oHasEventListener[ sKey ] = true;
console.log('button#' + sKey + ' on click listener added'); // just for debug purpose
}
}
},
oOnClickHandler = {
square: function() {
console.log('button#square on click event catched'); // just for debug purpose
removeEventListener('circle');
// do what ever you want to do after click on #square eg: $("canvas").on(...)
},
circle: function() {
console.log('button#circle on click event catched'); // just for debug purpose
removeEventListener('square');
// do what ever you want to do after click on #circle eg: $("canvas").on(...)
},
reset: addEventListeners
};
addEventListeners(); // add event listeners on startup
})( jQuery )
<button id="square">square</button>
<button id="circle">circle</button>
<button id="reset">reset</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you need some further explanations please feel free to leave a comment.

Jquery disabled an event, and re activate it later

1 - I've gat an html tag with data-needlogged attribute.
2 - I would like to disable all click events on it.
3 - When the user click on my element, I want to display the authentification popin.
4 - When the user will be logged, I would like to launch the event than I disabled before.
I try something like the following code but it miss the "...?" part.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// 2 - disabled all click events
jQuery('[data-needlogged]').off('click');
// 3 - Add the click event to display the identification popin
var previousElementClicked = false;
jQuery('body').on('click.needlogged', '[data-needlogged]="true"', function() {
previousElementClicked = jQuery(this);
alert('show the identification popin');
return false;
});
jQuery(document).on('loginSuccess', function() {
// 4 - on loginSuccess, I need to remove the "the show the identification popin" event. So, set the data-needlogged to false
jQuery('[data-needlogged]')
.data('needlogged', 'false')
.attr('data-needlogged', 'false');
// 4 - enable the the initial clicks event than we disabled before (see point 2) and execute then.
// ...?
jQuery('[data-needlogged]').on('click'); // It doesn't work
if (previousElementClicked) {
previousElementClicked.get(0).click();
}
});
</script>
Thanks for your help
Thank for your answer.
It doesn't answer to my problem.
I will try to explain better.
When I declare the click event on needlogged element, I don't know if there is already others click event on it. So, in your example how you replace the alert('play'); by the initial event ?
I need to find a way to
1 - disable all click events on an element.
2 - add a click event on the same element
3 - and when a trigger is launch, execute the events than I disabled before.
So, I found the solution on this stackoverflow
In my case, I don't realy need to disable and enable some event but I need to set a click event before the other.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
jQuery.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by #Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};
var previousElementClicked = false;
// set the needlogged as first click event
jQuery('[data-needlogged]').bindFirst('click', function(event) {
//if the user is logged, execute the other click event
if (userIsConnected()) {
return true;
}
//save the click element into a variable to execute it after login success
previousElementClicked = jQuery(this);
//show sreenset
jQuery(document).trigger('show-identification-popin');
//stop all other event
event.stopImmediatePropagation();
return false;
});
jQuery(document).on('loginSuccess', function() {
if (userIsConnected() && lastClickedElement && lastClickedElement.get(0)) {
// if the user has connected with success, execute the click on the element who has been save before
lastClickedElement.get(0).click();
}
});

codeschool jQuery Return Flight 5.10 on click handler failing

I am running into an odd issue with codeschools jquery course where my on click handler is not working. The question we are trying to solve in 5.10 is:
For starters create an event handler using on, that targets the
.see-photos link within each .tour. When this is clicked, run a
function that will add a class of is-showing-photofy to the tour.
You'll probably want to save a reference to this outside of your event
handler, and use that in the click event handler.
My current code attempt is:
$.fn.photofy = function() {
this.each(function() {
var tour = $(this)
tour.on('click.see-photos', 'button', function() {
$(this).addClass('is-showing-photofy');
});
});
}
$(document).ready(function() {
$('.tour').photofy();
});
and the error message I am getting is:
Your `on` `click` handler should watch for clicks on the `.see-photos` element within the current tour
Can anyone point me in the right direction?
I was missing the following:
prevent default
var tour = $(This)
Final Code:
$.fn.photofy = function() {
this.each(function() {
var tour = $(this);
tour.on('click.photofy', '.see-photos', function(event) {
event.preventDefault();
tour.addClass('is-showing-photofy');
});
});
}
$(document).ready(function() {
$('.tour').photofy();
});

javascript do something only once

i have the following function which lets my elements bounce every time i click on them. how can i achive that i can only click once on each element and if i click a second time to get an alert ("already clicked me")?
// Bounce On Click
function bounceOnClick(view) {
// If the view is a normal view (not a scrollview)
if (view instanceof View) {
// Listen to a click event
view.on("click", function (event) {
// Stop sending the click event to underlying views after this
event.stopPropagation()
// "Wind up" the spring
view.scale = 0.7
// And scale back to full size with a spring curve
view.animate({
properties: {
scale: 1.0
},
curve: "spring(1000,15,500)"
})
})
}
}
// Loop through all the exported views
for (var layerGroupName in PSD) {
bounceOnClick(PSD[layerGroupName]);
}
In JavaScript all objects are dynamic, so you can add properties to view:
view.on("click", function (event) {
if (this.clicked) {
alert("already clicked!");
} else {
// your code
this.clicked = true;
}
});
You can use jquery .one()
Jquery .one() :- Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Try this :
view.one("click", function (event) {
// Your Code
});
Something like this should do it:
function bounceOnClick(view) {
if (view instanceof View) {
// Listen to a click event, and run this handler only once.
view.one("click", function (event) {
event.stopPropagation();
view.scale = 0.7;
view.animate({
properties: {
scale: 1.0
},
curve: "spring(1000,15,500)"
})
// New event handler: notify the user the element was clicked before.
view.on("click", function (event) {
event.stopPropagation();
alert("already clicked me!");
})
})
}
}
This uses jQuery's .one() event handler to run the first function only once, and then assigns a new event handler with the "already clicked me!" alert.

Function calls inside jQuery plugin

I've nearly this code for defining the plugin instance:
$.fn.someplugin = function(opts) {
$(document).on('click', '.option-1', function() {
alert(1);
});
};
I use some code like this one to make my plugin work:
$('.selector-1').someplugin();
So jQuery in this way binds likely one click event listener to the document.
The question is, when I use my plugin multiple times, does it mean that jQuery binds 10 click events to the document?
$('.selector-1').someplugin();
$('.selector-2').someplugin();
$('.selector-3').someplugin();
$('.selector-4').someplugin();
$('.selector-5').someplugin();
$('.selector-6').someplugin();
$('.selector-7').someplugin();
$('.selector-8').someplugin();
$('.selector-9').someplugin();
$('.selector-10').someplugin();
In this way it binds 10 click listeners - because fn.someplugin is called 10 times, or just one?
Yes, it binds 10 click listeners to the $(document) object.
Every time you call someplugin() it will bind a new listener.
JSFIDDLE
If you want to add a single click handler to the document (inside of your plugin) you can do this:
(function ($) {
$.fn.someplugin = function(opts) {
alert("Another someplugin call.");
};
$(document).on('click', '.option-1', function() {
alert(1);
});
})($);
JSFIDDLE
You can do this to bind only one time :
(function ($) {
$.fn.someplugin = function (opts) {
return $(this).each(function (index, value) {
$(document)
.off('click', '.option-1')
.on('click', '.option-1', function (event) {
event.preventDefault();
alert(1);
});
});
};
})(jQuery);
$(document).ready(function () {
$('.selector-1, .selector-2').someplugin();
});
$(this).each allows you to bind multiple selectors.
.off() unbinds the event if it exists.
jsfiddle : http://jsfiddle.net/rWYS4/

Categories