Reputation: 3145
I have two jquery functions like this:
$(document).ready(init);
function init() {
$(".alphaleft").hover(function (g) {
$(".boxy,.yee").show();
},
function (g) {
$(".boxy,.yee").hide();
});
}
$(document).ready(init);
function init() {
$(".alpharight").hover(function (h) {
$(".tea,.coffee").show();
},
function (h) {
$(".tea,.coffee").hide();
});
}
But only one shows up at a time? Like if I comment one of them the other one works fine, and vise versa... Not sure what is causing this. Any suggestions? Been pulling my hair out for an hour now :(
edit: http://jsfiddle.net/W3TTh here is my jfiddle!
Upvotes: 1
Views: 380
Reputation: 63
It's because you're redeclaring the init
function.
Just wrap it in only one function like this:
$(document).ready(init);
function init() {
$(".alphaleft").hover(function (g) {
$(".boxy,.yee").show();
},
function (g) {
$(".boxy,.yee").hide();
});
$(".alpharight").hover(function (h) {
$(".tea,.coffee").show();
},
function (h) {
$(".tea,.coffee").hide();
});
}
Here's a working example: http://jsfiddle.net/DrYZV/
Upvotes: 0
Reputation: 94429
Pass the functions to ready
as anonymous functions.
$(document).ready(function(){
$(".alphaleft").hover(function (g) {
$(".boxy,.yee").show();
},
function (g) {
$(".boxy,.yee").hide();
});
});
$(document).ready(function () {
$(".alpharight").hover(function (h) {
$(".tea,.coffee").show();
},
function (h) {
$(".tea,.coffee").hide();
});
});
This prevents the conflict that is occurring because the functions are named the same. Since you declare the functions outside of a closure, the second function will override the first due to the shared name between the two and their global scope.
This fiddle demonstrates how the init
method is overridden. It can also be demonstrated by rearranging your code:
//Init function created
function init() {
$(".alphaleft").hover(function (g) {
$(".boxy,.yee").show();
},
function (g) {
$(".boxy,.yee").hide();
});
}
//Init function overridden
function init() {
$(".alpharight").hover(function (h) {
$(".tea,.coffee").show();
},
function (h) {
$(".tea,.coffee").hide();
});
}
//Init function called 2x after being overridden
$(document).ready(init);
$(document).ready(init);
Upvotes: 3
Reputation: 128781
There is no need for two ready
functions. There is also no need for calling a separate init
function:
$(document).ready(function() {
$(".alphaleft").hover(function () {
$(".boxy,.yee").show();
}, function () {
$(".boxy,.yee").hide();
});
$(".alpharight").hover(function () {
$(".tea,.coffee").show();
}, function ) {
$(".tea,.coffee").hide();
});
});
Upvotes: 2