Panton
Panton

Reputation: 13

hide div on mouseenter — but keep it

I have two divs — when mouseenter divA it should disappear and divB should appear. When mouseleave divB divA should show again and divB disappear. I’ve used this code to achieve it:

$("#divA").on("mouseenter", function() {
        $("#divA").hide();
        $("#divB").show();
    });
    $("#divB").on("mouseleave", function() {
        $("#divA").show();
        $("#divB").hide();
    });`

The only problem is that when divA hides another div (which used to sit under it) enters his place … So the question is if there’s a way to let divA disappear visually but not “physically”? Thank you!

Upvotes: 1

Views: 462

Answers (4)

William Carneiro
William Carneiro

Reputation: 360

Instead using display property, try using opacity property to do it:

$("#divA").on("mouseenter", function() {
    $("#divA").css("opacity", 0);
    $("#divB").css("opacity", 1);
});

$("#divB").on("mouseleave", function() {
    $("#divA").css("opacity", 1);
    $("#divB").css("opacity", 0);
});

Upvotes: 0

Aniket Suryavanshi
Aniket Suryavanshi

Reputation: 1584

Insted of hide() and show(), try setting CSS visibility property as below:

$("#divA").on("mouseenter", function() {
    $("#divA").css('visibility', 'hidden');
    $("#divB").css('visibility', 'visible');
});
$("#divB").on("mouseleave", function() {
    $("#divA").css('visibility', 'visible');
    $("#divB").css('visibility', 'hidden');
});

Upvotes: 0

Renan Borges
Renan Borges

Reputation: 610

I guess you want something related to the css property called visibility. This property hides the element but 'keeps it there'.

https://www.w3schools.com/CSSref/pr_class_visibility.asp

And looks like you are using jQuery. So I searched a bit and I found this answer that explains precisely how to change the visibility of an element by using jQuery.

https://stackoverflow.com/a/9614662/2250437

Might be useful for you.

Upvotes: 0

dwb
dwb

Reputation: 2624

Check out this answer for more details on the differences between display, visiblility and opacity. In the link, what you're looking for is the ones which have a tick under occupies space.

Essentially you want to set its css property

element.hidden {
    opacity: 0;
}

which visually hides the element, but it can still be interacted with.

Upvotes: 1

Related Questions