Angelo Chrysoulakis
Angelo Chrysoulakis

Reputation: 946

Jquery .toggle() and the browser back button

I have a fairly simple layout with a very strange outcome.

$(".main").on("hover", ".js_post", function () {
$(this).children('.js_del').toggle();
});

Essentially, when a user hovers over the .js_post div, the .js_del div is toggled. Here's the css that hides .js_del:

.js_del { display:none; }

Now, when the cursor hovers over .js_post, the .js_del div toggles, as expected. But, when the user clicks a link within the .js_post div and then clicks the browser back button, strange things happen...

In FF, all works as one would expect (i.e., the browser interprets the click as a mouseleave and toggles the .js_del.)

In Safari, however, when the user clicks back, the browser applies toggle in reverse (i.e., .js_del is showing and when the cursor hovers over .js_post, the .js_del link disappears.)

Even weirder...

I decide to add a handler to manually hide the .js_del div whenever an 'a' element within .js_post is clicked like this:

$(".js_post").find("a").click(function () {
    $(this).parents('.js_post').children('.js_del').hide();
});

And now, when viewed in Safari, all works as expected but in FF, it's reversed (i.e., .js_del is showing and when the cursor hovers over .js_post, the .js_del link disappears)!

Any thoughts??? Thanks!

Upvotes: 0

Views: 879

Answers (1)

DefyGravity
DefyGravity

Reputation: 6031

Because the back button is not making the page cacheing behave the same, and you can't be sure of the dom element state, toggle() calls can be rough. I split out the mouseenter and mouseleave instead of hover(), and specifically called out the visibility within the child selector. I also threw on a .hide() call at the very end to standardize the .js_del dom element visibility state regardless of back button browser issues.

js

$(".main").on({
  "mouseenter":function(evt){
    $(this).children('.js_del:hidden').toggle();
  },
  "mouseleave":function(evt){
    $(this).children('.js_del:visible').toggle();
  }
}, ".js_post", null).find('.js_del:visible').hide();

Upvotes: 1

Related Questions