I have two buttons:
<button id="Ck">Click</button>
<button id="Me">Mouseenter</button>
I want to give the user chance to choose how to open my jQuery animated menus (on click or on mouseenter), by clicking one of this two buttons.
Is there any way to switch betwen these methods? And what I have to do to keep these chooses even when the page is refreshed?
Easily.
First, give the buttons a class:
<button id="Ck" class="ClickMouseenter">Click</button>
<button id="Me" class="ClickMouseenter">Click</button>
Then check the id when the button is clicked, and assign appropriately:
$('.ClickMouseenter').on('click',function(){
var id = this.id,
$menu = $('#MenuExample');
$menu.off();
if(id==='Ck'){
$menu.on('click',function(){
// click magic;
});
} else {
$menu.on('mouseenter',function(){
// mouseenter magic;
});
}
});
Or if they perform the same function just with different handlers:
// yay for faster code processing!
$('.ClickMouseenter').on('click',function(){
var id = this.id,
action = (id==='Ck' ? 'click' : 'mouseenter');
$('#MenuExample').off().on(action,function(){
// action magic;
});
});
The .off()
removes the assignment that was existing (click
or mouseenter
), and then a new .on()
handler is applied depending on the id
of the button
you clicked.
In regards to keeping these settings upon page refresh ... my first inclination is using sessionStorage
(note: this will only work on IE8 and above; if you're coding for IE6 or IE7, you're out of luck). Create a function from the event which includes sessionStorage
assignment:
function setMenu(action){
$('#MenuExample').off().on(action,function(){
// action magic;
});
sessionStorage.menuType = action;
}
$('.ClickMouseenter').on('click',function(){
var id = this.id,
action = (id==='Ck' ? 'click' : 'mouseenter');
setMenu(action);
});
And now you can call it on page load to reassign the choice if necessary, with a default fallback:
if(sessionStorage.length > 0){
setMenu(sessionStorage.menuType);
} else {
setMenu('mouseenter');
}
This is obviously an oversimplified version, but should give an idea to start with.