I have a script that hides a div by default and slideToggles it when I click a link (see http://zarin.me — the contact link). Here’s the code I’m using:
<script>
$(document).ready(function(){
$("#contact-drawer").hide();
$(".toggle-drawer").show();
$('.toggle-drawer').click(function(){
$("#contact-drawer").slideToggle();
});
});
</script>
My problem is that when the page loads, the whole div is displayed for a split second, and then hidden. This can be a bit a jarring sometimes. What do I need to fix so that the div doesn’t display on load?
As Darko Z said below, the reason for this flickering is that there is a delay between the browser rendering the
#contact-drawerelement and your JavaScript code running. The browser is doing what it’s told by your CSS and HTML and displaying the element, and only after that is it indicating the document has finished parsing (DOM ready) and triggering your JavaScript.There are a few ways to fix this (with varying compatibility). Essentially you need to get code interpreted in between or before the element rendering and the DOM being ready.
To patch with JavaScript, you could add an inline script immediately after the element to set it’s display to hidden. This code would be executed immediately as the page is interpreted rather than when the DOM is ready. I believe this is the simplest and safest method in terms of accessibility.
Plain JavaScript:
or with jQuery:
To fix with pure CSS you would set the element’s display property to ‘none’. Note that with this solution, if JavaScript is disabled the form will not be accessible.
CSS
To fix with CSS AND maintain a working page when javascript is disabled you could use an additional
:targetCSS selector and change your link and JavaScript a little. The target selector is not 100% compatible with older browsers, but it’s more accessible than the plain CSS version above.CSS
Add the same style as above, and a copy setting display to block with the selector
:target. This makes it so when you navigate to http://zarin.me/#contact-drawer, the :target style will activate and #contact-drawer will display.HTML
Change the anchor href from
#to#contact-drawerso that when the link is click, it activates the:targetselector.JavaScript
Add
return falseat the end of the function to stop the browser navigating to#contact-drawer(and activating the:targetselector) when.toggle-draweris clicked.