coder_bro
coder_bro

Reputation: 10773

JQuery hide div - resulting in javascript error

I have the following html in page:

<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>    
<script>
        function hideIt() {
            $(this).hide("slow");
            return true;
        }         
    </script>
</head>
<body>
<div onclick="hideIt();">
         hello world
    </div>
</body>

When I click on the div, it results in the following JavaScript error:

Line: 53 Error: 'this[...].style' is null or not an object

Any solutions?

Upvotes: 0

Views: 411

Answers (5)

rahul
rahul

Reputation: 187110

this refers to the current object. For your code to work you have to pass a reference to the div element by passing this inside the function call.

The main advantage of using jQuery is to separate markup and script. So you won't write event handlers inside the markup. You can write event handlers only after the DOM is ready.

<head>
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>    
    <script>
        $(function(){
            $("#divToHide").click(function(){
                $(this).hide();
            });
        });        
    </script>
    </head>
    <body>
    <div id="divToHide">
             hello world
        </div>
    </body>

A detailed reading on Unobtrusive JavaScript

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382909

Try this:

<script>
    function hideIt(item) {
        $(item).hide("slow");
        return true;
    }         
</script>

<div onclick="hideIt(this);">
     hello world
</div>

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

$(this) will only be your DIV if you bind the event with jQuery:

$('#myDiv').click(hideIt);

The way you're doing it, you need to pass a reference to the object:

<div onclick="hideIt(this);">

and use that in your function:

    function hideIt(obj) {
        $(obj).hide("slow");
        return true;
    } 

Upvotes: 0

Darmen
Darmen

Reputation: 4881

There are no definition to this object in that scope. Use selectors instead:

<div class="ready_to_hide">
     hello world
</div>

$('.ready_to_hide').click(function(){
   $(this).hide();
});

Upvotes: 1

marcgg
marcgg

Reputation: 66535

This should fix it

<div onclick="hideIt(this);">

and

function hideIt(o) {
            $(o).hide("slow");
            return true;
        }     

Upvotes: 0

Related Questions