Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice (jQuery, CSS): How to initialize hidden elements that will toggle visible?

Tags:

jquery

css

fade

Stack is warning me this is a subjective question, and will likely be close, but I'm going to try this anyway.

I have a set of control buttons attached to pictures in a gallery. These are to be initially hidden, and toggle visible when the mouse hovers over the image. The question I have is this:

Should these buttons be set to hidden in the stylesheet or stay visible and be hidden by jQuery when they load? I want graceful degradation, so it seems like initializing this in the CSS is a bad idea if I want these to be visible if javascript isn't enabled.

On top of this, I'm using Ajax to load pages of these images. If I do this using the jQuery hide, it doesn't affect those that load from an ajax request, since it only triggers on $(document).ready(). I've tried using live('ready'), but learned that that event isn't supported in live().

So what is the best practice for something like this? It seems like there's a lot of pros and cons for doing this either way (css vs. document.ready), and if they're hidden by the default CSS, the buttons will toggle fine with ajax pagination. But if javascript isn't enabled, the functionality of the buttons will be lost. Does anyone have advice for this?

Note: I didn't mention it originally, but it is significant. I'm currently using fadeToggle() to accomplish my transition, which may be what's complicating this whole issue. The solutions so far all appear to work, but not so much when fading is introduced.

like image 486
Josh Kovach Avatar asked Feb 25 '23 13:02

Josh Kovach


2 Answers

If you're trying to change the style of elements loaded via Ajax, it's almost like you're trying to hit a moving target. I would create two declarations in my stylesheet - one for hidden, one for visible - and then toggle them based on a class attached to the body tag (or any other containing tag).

Like so:

body .mybutton {
  display:block;
}

body.loaded .mybutton {
  display:none;
}

Then in your JS file:

$(document).ready(function() {
  $('body').addClass('loaded');
});

This way, any elements that have the class name mybutton - current and future - will have the appropriate style applied.

like image 200
Gary Chambers Avatar answered Feb 27 '23 03:02

Gary Chambers


You hide with CSS initially using display:none; then use jQuery's toggle() to show and hide again. This is the best way to do it. As for people that do not have JavaScript enabled, i wouldn't worry about that. They make 1% of users. Everyone have JavaScript enabled.

Check working example http://jsfiddle.net/znJxh/

like image 32
Hussein Avatar answered Feb 27 '23 04:02

Hussein