how to make div click-able?

242,665

Solution 1

Give it an ID like "something", then:

var something = document.getElementById('something');

something.style.cursor = 'pointer';
something.onclick = function() {
    // do something...
};

Changing the background color (as per your updated question):

something.onmouseover = function() {
    this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
    this.style.backgroundColor = '';
};

Solution 2

<div style="cursor: pointer;" onclick="theFunction()">

is the simplest thing that works.

Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it on a list apart for good practices on not just solving this particular problem but in markup design in general.

Solution 3

The simplest of them all:

<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>

Solution 4

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

Solution 5

I suggest to use a CSS class called clickbox and activate it with jQuery:

$(".clickbox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
 });

Now the only thing you have to do is mark your div as clickable and provide a link:

<div id="logo" class="clickbox"><a href="index.php"></a></div>

Plus a CSS style to change the mouse cursor:

.clickbox {
    cursor: pointer;
}

Easy, isn't it?

Share:
242,665
omg
Author by

omg

Updated on May 11, 2020

Comments

  • omg
    omg almost 4 years
    <div><span>shanghai</span><span>male</span></div>
    

    For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a

    javascript function,how to do that job?

    EDIT: and how to change the background color of div when mouse is on?

    EDIT AGAIN:how to make the first span's width=120px?Seems not working in firefox