Reputation: 25
Hello I have jquery that looks like this:
var autoStart = true;
jQuery(document).ready(function($) {
$('.royalSlider').each(function() {
var autoStart = true;
var slider = $(this);
var button = $('<button>pause</button>').insertAfter(slider).click(function() {
if(autoStart) {
$(this).html('play');
} else {
$(this).html('pause');
}
autoStart = !autoStart;
slider.royalSlider('toggleAutoPlay');
});
});
I would like to assign some css to the button in this code, how do I assign a class to this button? Thanks
Upvotes: 0
Views: 140
Reputation: 5993
#1 The easiest way would be to just include class='class-name'
in your definition of the button.
#2 Second easiest way would be to add id='button-name'
to the definition, then do:
$("#button-name").addClass("class-name")
... after the button is inserted into the DOM.
#3 Third / hardest way would be not to add a class
or id
, and to work from the contents. You'd do:
$("button:contains('pause')").addClass("class-name");
#1 is definitely the fastest also. No extra processing at all! Just do this:
var button = $('<button class="class-name">pause</button>') ...
To optimize even further, do this:
function toggleAutostart( autoStart ) {
if ( autoStart == undefined ) autoStart = true;
if(autoStart) {
$(this).html('play');
} else {
$(this).html('pause');
}
autoStart = !autoStart;
slider.royalSlider('toggleAutoPlay');
}
jQuery(document).ready(function($) {
$('.royalSlider').each(function() {
$('<button class="class-name">pause</button>')
.insertAfter( $(this) )
.click( toggleAutostart );
);
});
Upvotes: 3
Reputation: 318182
Create the element the jQuery way
var btn = $('<button />' , {
text : 'pause',
'class' : 'myClass',
click : handleClick
}).insertAfter(slider);
function handleClick() {
$(this).html(autoStart ? 'play' : 'pause');
autoStart = !autoStart;
slider.royalSlider('toggleAutoPlay');
}
Upvotes: 0
Reputation: 1387
$(this).addClass('classname');
Probably you want to check existence first... look at the reference: http://api.jquery.com/addclass/
Upvotes: 0