I'm trying to make a button, to switch the site background once clicked. And of course the setting needs to be saved in a cookie, for it to stick.
How can I combine the two scripts, so that once the button is clicked, it stays switched, with the background? Or is dependend on the body class 'clicked'?
I found a way to switch and save the background in a cookie:
$(document).ready(function() {
var body_class = $.cookie('body_class');
if(body_class) {
$('body').attr('class', body_class);
}
$("#switch").click(function() {
$("body").toggleClass('clicked');
$.cookie('body_class', $('body').attr('class'));
});
});
And the button is switched from switch_on.png to switch_off.png with this:
$(function(){
$(".toggle-swap").click(function() {
if ($(this).attr("class") == "toggle-swap") {
this.src = this.src.replace("switch_on.png","switch_off.png");
} else {
this.src = this.src.replace("switch_off.png","switch_on.png");
}
$(this).toggleClass("on");
});
});
My button:
<div id="switch"><a href="#"><img class="toggle-swap" src="../img/switch_on.png" alt=""></a></div>
I'd combine that into one function, eg like this:
$(function() {
// Create a variable for the current state
var body_class;
// Cache some elements
var $body = $('body'), $switch = $('.toggle-swap');
// Define a function that toggles background + button
var toggleBodyClass = function(event) {
// Toggle the images
if (body_class) {
$switch[0].src = $switch[0].src.replace("switch_off.png","switch_on.png");
body_class = '';
} else {
$switch[0].src = $switch[0].src.replace("switch_on.png","switch_off.png");
body_class = 'clicked';
}
// Toggle some css classes (body + button)
$body.toggleClass('clicked');
$switch.toggleClass('on');
// Update the cookie
$.cookie('body_class', body_class);
// Prevent the browsers default behavior
if (event) event.preventDefault();
};
// Set the initial state
if ($.cookie('body_class')) {
toggleBodyClass();
}
// Bind the event handler
$switch.click(toggleBodyClass);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.