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

Stack warns me that this is a subjective question and will probably be close, but I will try to do it anyway.

I have a set of control buttons attached to images in the gallery. They should be hidden initially and switch when the mouse hovers over the image. I have a question:

Should these buttons be hidden in the stylesheet or stay visible and hide when jQuery loads? I want elegant degradation, so it seems that initializing this in CSS is a bad idea if I want them to be visible if javascript is not included.

In addition, I use Ajax to load pages of these images. If I do this using jQuery hide, this does not affect those loaded from the ajax request, since it only runs on $(document).ready() . I tried using live('ready') , but found out that this event is not supported in live() .

So what is best for something like that? There seems to be a lot of pros and cons to this anyway (css versus document.ready), and if they are hidden by default CSS, the buttons will switch using ajax pagination. But if javascript is not enabled, the functionality of the buttons will be lost. Anyone have any advice for this?

Note. I did not mention this initially, but it is important. I am currently using fadeToggle() to complete my transition, which can be a complication of this whole problem. Solutions still work, but not so much when attenuation is introduced.

+4
source share
2 answers

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

Same:

 body .mybutton { display:block; } body.loaded .mybutton { display:none; } 

Then in your JS file:

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

Thus, all elements that have the class name mybutton - current and future, will have the appropriate style.

+6
source

First you hide using CSS with display:none; , then use jQuery toggle () to show and hide again. This is the best way to do this. As for people who don't have JavaScript, I would not worry about that. They make up 1% of users. Everyone has JavaScript.

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

+2
source

Source: https://habr.com/ru/post/1347343/


All Articles