views:

51

answers:

5

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?

A: 

This should fix it

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

and

function hideIt(o) {
            $(o).hide("slow");
            return true;
        }     
marcgg
+1  A: 

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();
});
Darmen
There is — the `window` object. (It isn't a useful definition though)
David Dorward
A: 

$(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;
    } 
David Hedlund
A: 

Try this:

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

<div onclick="hideIt(this);">
     hello world
</div>
Sarfraz
+1  A: 

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

rahul