J82
J82

Reputation: 2387

make div clickable with jquery

jsfiddle: http://jsfiddle.net/FgZnK/1/

Clicking on the box goes to a page not found. How can I make this work?

HTML

<div class="myBox"></div>

jQuery

$(".myBox").click(function(){
    window.location=$(this).attr("http://google.com");
     return false;
});

Upvotes: 6

Views: 42911

Answers (7)

Jay Brunet
Jay Brunet

Reputation: 3750

Open in new window....

    $("#whatever").click(function() {
        window.open(
          'https://www.example.com',
          '_blank' // open in new window
        );
    });

Upvotes: 1

schellmax
schellmax

Reputation: 6094

$(".myBox").click(function(){
    window.location.href="http://google.com";
    return false;
});

Upvotes: 0

krtek
krtek

Reputation: 26597

This is the faulty line :

window.location=$(this).attr("http://google.com");

This doesn't make any sense, you're trying to change the location to the value of the attribute named "http://google.com" of your div.

Just correct it like this :

$(".myBox").click(function(){
    window.location= "http://google.com";
     return false;
});

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

In this chunk here:

$(".myBox").click(function(){
window.location=$(this).attr("http://google.com");
 return false;
});

You're actually trying to read the non-existent attribute named http://google.com.

Instead, just use:

$(".myBox").click(function(){
    window.location = 'http://google.com';
});

If instead you want the actual destination to be in the mark up rather than the script, use:

$(".myBox").click(function(){
    window.location = $(this).attr('href');
});

and put an href attribute on your DIV, just like you would on an A link.

There's no need for return false in any of these handlers because a DIV doesn't have a default action that needs preventing, unlike a normal link.

Upvotes: 2

Paweł Gościcki
Paweł Gościcki

Reputation: 9604

This is the correct code:

$(".myBox").click(function() {
    window.location = "http://google.com";
});

Upvotes: 15

Alex Wayne
Alex Wayne

Reputation: 187034

http://jsfiddle.net/FgZnK/2/

HTML

<div class="myBox" data-href="http://google.com/">
</div>

JS

$(".myBox").click(function(){
    window.location = $(this).attr("data-href");
    return false;
});

Upvotes: 6

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17295

window.location="http://google.com";

Upvotes: 0

Related Questions