blank_kuma
blank_kuma

Reputation: 345

jQuery .hide() element not working

I am trying to do a simple .hide() with jQuery but it's not working for some reason. I tried it with jsfiddle (http://jsfiddle.net/j0a2zbyb/1/) but it didn't work. Any help would be appreciated.

HTML code

    <script>
        $(document).ready(function(e){
            e.preventDefault();
            $(".error").hide();

        });
    </script>

CSS code

.error{
width: 300px;
height: auto;
background-color: #FF6C6C;
border: solid 2px #000;
}

Upvotes: 0

Views: 670

Answers (4)

Guffa
Guffa

Reputation: 700152

The ready event handler is not called with an event object like other event handlers. It's called with a reference to the jQuery object (intended to be used when the noConflict method has been used).

When you try to call preventDefault on the value passed to the function, you get an error becase there is no such method in that object.

If you avoid the preventDefault call, it works fine:

$(document).ready(function(){
  $(".error").hide();
});

Side note: An alternative to using hide in the ready event would be to use display:none; in the CSS. That way there is no risk that the element would be visible for a short moment while the page loads, as the CSS ensures that it's invisible as soon as it is created.

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98861

$(document).ready(function(){
$(".error").hide();
});
.error{
width: 300px;
height: auto;
background-color: #FF6C6C;
border: solid 2px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="error"> error</div>
<div class="noerror"> noerror</div>

Upvotes: 0

ctb
ctb

Reputation: 1222

I think you're over-thinking it. Try:

<script>
    $(document).ready(function(){
        $(".error").hide();
    });
</script>

Upvotes: 0

Michelangelo
Michelangelo

Reputation: 5948

Do not prevent default:

    $(document).ready(function(e){

        $(".error").hide();

    });

Upvotes: 0

Related Questions