Javascript Onclick run multiple times

Asked

Viewed 32 times

0

I need to make a border appear and disappear every time I click. I can’t use jQuery or eventlist. I know I should use IF but I don’t know how. What I can do so far is click and make it appear. It should be around the paragraphs. I appreciate your help

 var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++){
    elements[i].onclick=function(){
    this.style.border="dashed black 1px";

}

}

  • She must disappear when? A certain time after appearing?

2 answers

0

Just check if the element has the edge

if (this.style.border) {
    this.style.border="";
} else {
    this.style.border="dashed black 1px";
}

Example

var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++){
    elements[i].onclick=function(){
      if (this.style.border) {
        this.style.border="";
      } else {
        this.style.border="dashed black 1px";
      }
    }

}
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>

  • Thank you!!! Perfect!

  • Most recommend using @Oeslei’s reply.

0

Use css to display the border. So just use the method toggle to add / remove the class responsible for adding the border.

In the JS:

this.classList.toggle('com-borda');

In the CSS:

.com-borda {
    border: dashed black 1px;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.