Reputation: 9415
I have a button on my website that I'd like to use to toggle on and off a description box. So when the button is clicked, I want it to show an image preview when you hover over certain elements on the page, but when the button is deselected, it should not show any image previews.
I created a jQuery function and pass it a boolean based on whether the image preview window should or should not show. However, it seems like the hover function ( $(".node").hover(function(e)) is being called regardless of the boolean. What am I doing wrong?
$('.textIcon').click(function(){
if(textCount %2 == 0){
// show preview images
imagePreview("true");
textCount++;
}
else{
// hide preview images
imagePreview("false");
textCount++;
}
});
jQuery script:
<script>
// create pop up preview box for each step when text labels are off
this.imagePreview = function(on){
console.log("in imagePreview, on: " + on);
/* CONFIG */
xOffset = 50;
yOffset = 140;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
if(on=="true"){
console.log("ON");
$(".node").hover(function(e){
console.log("node hover");
// title of step
this.t = $(this).data('title');
this.title = "";
// image url of step
this.href = $(this).data('image');
// show title + image for preview
if(this.href != null){
var c = (this.t != "") ? this.t + "<br>": "";
$("body").append("<p id='preview'>" + c + "<img src='"+ this.href +"' alt='Image preview' style='margin-top:5px' />" +"</p>");
}
// just show title for preview
else{
var c = (this.t != "") ? this.t : "";
$("body").append("<p id='preview'>"+ c +"</p>");
}
$("#preview")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px")
.fadeIn("fast");
},
function(){
this.title = this.t;
$("#preview").remove();
});
$(".node").mousemove(function(e){
var dotPosition = $(this).position();
$("#preview")
.css("top",(dotPosition.top + xOffset) + "px")
.css("left",(dotPosition.left + yOffset) + "px");
});
}
};
</script>
Upvotes: 0
Views: 187
Reputation: 443
You are assigning a function to the hover event everytime you call imagepreview() instead try assigning the hover event once and check inside if it should show previews or not.
Try something like:
var showOnHover = false; // determines behaviour
$('.textIcon').click(function(){ showOnHover = !showOnHover; }); // change behaviour onclick
// we assign it once
$(".node").hover(function(e){
// we look if we need to do something now
if (showOnHover){
// onHover activated
// do your stuff
}
// else shouldn't show
});
Upvotes: 1