Skip to main content

[WP] Where to put slider JavaScript API code?

The slider is initialized in the footer of WordPress page and in document.ready event.

To put JavaScript code that relies on slider instance use new_rs_after_js_init_code action.

// Add this to your theme functions.php
function add_additional_rs_code() {
?>
// put JS code here


// For example: get slider instance (if it's single on page)
var sliderInstance = $('.royalSlider').data('royalSlider');

// show message each time slide changes
sliderInstance.ev.on('rsAfterSlideChange', function() {
alert('Test slide index ' + sliderInstance.currSlideId);
});

// end of JS code
<?php
}
add_action('new_rs_after_js_init_code', 'add_additional_rs_code');

Note, that if you have multiple sliders on page, you'll need to select specific one (by using narrower selector), or loop through them, for example:


function add_additional_rs_code() {
?>
$('.royalSlider').each(function() {
// instance of single slider
var sliderInstance = $(this).data('royalSlider');


});
<?php
}
add_action('new_rs_after_js_init_code', 'add_additional_rs_code');

If you want to run the code before the slider initialization, you may use new_rs_before_js_init_code action.

Slider JavaScript API documentation is here.

Example: custom alt attribute for lazy-loaded images based on the caption

// Add to your theme functions.php
function slider_modify_alt_attribute() {
?>
var sliderInstance = $('.royalSlider').data('royalSlider');
sliderInstance.ev.on('rsAfterContentSet', function (e, slideObject) {
var img = slideObject.holder.find('img').eq(0);
if (img && img.length && slideObject.caption) {
img.attr('alt', slideObject.caption.text());
}
});
<?php
}
add_action('new_rs_after_js_init_code', 'slider_modify_alt_attribute');