How to create a clickable div? [closed]

1

I have a div on my site and want to make it clickable through Javascript. How do I do that? Thank you.

    
asked by anonymous 13.03.2018 / 16:58

4 answers

1
<div id="myDiv">
   Click me
</div>

<script>
  document.getElementById("myDiv").onclick = function() {
   alert('Clicked!');
  };
</script>
    
13.03.2018 / 17:15
1

One way to "create" a clickable div would be:

#clicavel{
cursor: pointer;
}

#clicavel:hover{
color: red;
}

#clicavel:active{
color: blue;
}
<script>
function executaAcao(){
alert("Eu vou para o Google");
window.location = "http://google.com";
}
</script>
<div id="clicavel" onclick="executaAcao()">CLIQUE AQUI</div>

We use the onclick method to assign a javascript function to the html element and the :hover and :active attributes to customize the style of the element as the mouse actions.

    
13.03.2018 / 17:15
0

function res(){
  alert("Vc devia pesquisar mais")
}
div{
  cursor: pointer;
}
<div onClick="res()">
Click aqui
</div>
    
13.03.2018 / 17:19
0

There are many ways to do this, from adding onclick to tag itself to creating events:

// função
function f(){
   console.log("div clicada!");
}

// EventListener
document.querySelector("#minhadiv1").addEventListener("click", f);

// onclick
document.querySelector("#minhadiv3").onclick = f;
#minhadiv1,
#minhadiv2,
#minhadiv3{
   cursor: pointer;
}
<div id="minhadiv1">Clique-me</div>
<br />
<div id="minhadiv2" onclick="f()">Clique-me</div>
<br />
<div id="minhadiv3">Clique-me</div>

You can add the style pointer with CSS to change the mouse cursor (see code above).

    
13.03.2018 / 17:33