Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my javascript onclick work with div?

I am trying to turn a <div> into a link to local HTML document (./lilo/index.html) using JavaScript.

HTML

<div class="pagelist_item" onClick="goto("./lilo")">
    <h4>Test Button</h4>
    <h6>Discription</h6>
</div>

JavaScript

function goto(url){
    window.location = url;
    alert(url);
}

See http://jsfiddle.net/6HHTd/

But when I click the button, nothing happens.

Why does this not work?

like image 443
abaft Avatar asked Jun 21 '26 14:06

abaft


2 Answers

Your quotes are incorrect in this line:

<div class="pagelist_item" onClick="goto("./lilo")">

jsfiddle even shows the error in red text.

Using apostrophes makes it easier to fix:

<div class="pagelist_item" onClick="goto('./lilo')">

To clarify, in "hi "there" you" the second double-quote matches with the first, closing the string and causing an error with the rest of the expression. Escaping the quotes with back-slashes works "hi \"there\" you" but embedding apostrophes (single-quotes) within double-quotes is often easier. (JavaScript is happy to use either single or double-quotes to delimit strings.)

Also rename your function from goto, as it is a reserved keyword.

like image 167
Andy G Avatar answered Jun 24 '26 03:06

Andy G


Use jquery as follows

$('.pagelist_item').click(function(){
     window.location="./lilo";
});

Fiddle

like image 31
Nithesh Narayanan Avatar answered Jun 24 '26 03:06

Nithesh Narayanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!