Reputation: 10626
I have this piece of code. Basically, what I like to do is, when clicked on cpu_div, I like to show the all_cpu div and when clicked on, all_cpu div, I like to show cpu_div. The idea is to switch between divs back and forth:
html code:
<div id="cpu_all"> </div>
<div id="cpu_div"></div>
var serverA = "http://url/cpu.png";
$("#cpu_div").click(function () {
var myImage = new Image();
$(myImage).load(function () {
$('#all_cpu').show();
$("#all_cpu").html(myImage);
}).error(function () {
$('#all_cpu').hide();
}).attr('src', serverA)
});
$("#all_cpu").click(function () {
$('#all_cpu').hide();
$("#cpu_div").show();
});
when clicked on cpu_div, it brings up all_cpu div but when clicked on all_cpu div, nothing is happening. Any one can chime in to see what is wrong here?
Upvotes: 0
Views: 166
Reputation: 318182
$("#cpu_div, #all_cpu").on('click', function() {
$("#cpu_div, #all_cpu").not(this).show();
$(this).hide();
});
If that's still not working, give this a go:
$(document).on('click', '#cpu_div, #all_cpu', function() {
$("#cpu_div, #all_cpu").not(this).show();
$(this).hide();
});
Also, using the native onload function would be a better idea in my opinion:
$("#cpu_div, #all_cpu").on('click', function() {
var myImage = new Image();
myImage.src = 'http://url/cpu.png';
myImage.onload = function() {
//do stuff
}
});
Upvotes: 1
Reputation: 6071
The problem is, that you set the attr('src') after you try to load the image. Changing your code to
$(myImage).attr('src', serverA).load(...)
will fix that.
Upvotes: 0
Reputation: 4372
As @Adrian has suggested, we can't know everything that's going on without your HTML, but it sounds like you want to toggle()
the visibility of those two divs
$("#all_cpu,#cpu_div").click(function () {
$('#all_cpu').toggle();
$("#cpu_div").toggle();
});
Upvotes: 0