kiarashi kiarashi - 2 months ago 15
Javascript Question

Override jQuery on click handler function

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 )
});

Answer

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>

Comments