Q239
Q239

Reputation: 23

styling elements with Javascript without being noticed

I have a webpage which has content layout like 1,2,3 in markup (and also for no-js ) while visually I want it to be 2,3,1.

I'm using Javascript (jQuery) to swap their position. But the problem is, the Javascript code is executed after page loads and therefore the swap process can be obviously seen.

The only solution (and a bad one) I can think of now is to hide the whole body first and restore body when the swap is done.

$(function() {
    $("#div2, #div3").insertBefore("#div1");
    $("body").css({display: "block"});
});
<body style="display: none;">
...
<div id="div1">...</div>
<div id="div2">...</div>
<div id="div3">...</div>
...
<!-- in case JS is disabled, use css to restore -->
<!-- style should not be here, that's why I said it's a bad one. -->
<style type="text/css">
body {display: block !important;}
</style>
</body>

Anyone got a better idea?

Upvotes: 2

Views: 62

Answers (1)

Daniel O&#39;Hara
Daniel O&#39;Hara

Reputation: 13438

Try executing JavaScript instantly after those three elements:

<div id="div1">...</div>
<div id="div2">...</div>
<div id="div3">...</div> 
<script type="text/javascript"> $("#div2, #div3").insertBefore("#div1"); </script>

Of course, it's a pollution of your HTML, but, in any case, it's better than hiding the whole body element (the page will flicker in some old browsers).

Upvotes: 2

Related Questions