简体   繁体   中英

Using javascript to hide div

I am using Javascript to hide a search box until a box is clicked. That works fine.

However when the page is first loaded, you can see the search box there and then it disappears once the page has fully loaded.

How can I make it hide and not show at all until my button is clicked..

This is the Javascript:

<script type="text/javascript">
$(function(){
$(".search").hide();
$(".clicktosearch").on("click", function(){
    $(".search").slideToggle("600");

.search is the actual search box .clicktosearch is the box the user must click for the actual search box to show up.

They only thing I have tried is to move the Javascript above the html box but, to no luck, now I am asking you all on SOF.

You need to use display:none in the CSS to hide it initially. The javascript only executes after the page has loaded so you will always see it briefly before the javascript kicks in.

Hide it using css .

.search { display:none;}

The reason for this happening is the javascript getting loaded after the css and HTML take affect. Hide it using CSS, the time lag before the div hides will be less.

You have the .hide inside of document.ready, $(function(){ is short for $(document).ready(function() {

So just put it before the document.ready and it should work...

<script type="text/javascript">
$(".search").hide();         //moved this line too here
$(function(){
$(".clicktosearch").on("click", function(){
    $(".searchr").slideToggle("600");

although, What I personally would prefer is just in your css hide it.

Like so,

.search { display: none; }

You'll have to touch the CSS.

.search {
  height: 0px;
}

Then in your JavaScript:

$(".clicktosearch").on("click", function(){
    $(".search").slideToggle("600");
});

This is what you need:

CSS

.search { display:none;}

JS

$(".clicktosearch").on("click", function(){
    $(".search").slideToggle("600");
});

I removed $(".search").hide(); because it's unneeded and may cause other problems. (JQuery doesn't need to hide something that's already hidden via CSS.)

BTW: If there's only one element that matches .search , it should really be an id and so #search . Same goes for .clicktosearch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM