I have a div on my site and want to make it clickable through Javascript. How do I do that? Thank you.
I have a div on my site and want to make it clickable through Javascript. How do I do that? Thank you.
<div id="myDiv">
Click me
</div>
<script>
document.getElementById("myDiv").onclick = function() {
alert('Clicked!');
};
</script>
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.
function res(){
alert("Vc devia pesquisar mais")
}
div{
cursor: pointer;
}
<div onClick="res()">
Click aqui
</div>
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).