How to acquire the value of the onclick() event

Asked

Viewed 144 times

3

I want an "if" that your condition is based on the location of the user’s click, but I have no idea how to refer to it. I believe on that basis you understand what I want to happen:

if (onclick == window) {executar bloco de código}

If you want to see my code:

HTML5:(only revealing code)

<li><img src="Backgrounds/Foto7.jpg" onclick="myFunction(this.src)"></li>...<div id="open">/*Imagem criada aqui*/</div></body>

Javascript

function myFunction(a) {
var NewImg = document.createElement('IMG');
document.getElementById('open').appendChild(NewImg);
NewImg.className = "open";
NewImg.setAttribute('src',a);
var DELIMG = document.getElementById('open');
if (onclick == NewImg){DELIMG.removeChild(NewImg)}
}
  • vc can refer to a div or an element, by Document.getElementById("suaDiv"), in case it is a div...

  • So? if (onclick !== getElementById("myDiv")) {}

2 answers

4


Generally when you want if (onclick == window) {executar bloco de código} use the .addEventListener.

It can be used in DOM elements, in window, in objects, etc.

In the case of window is simple,

window.addEventListener('click', function(event){
    alert('houve um clique na window!');
    alert('O clique foi em cima do elemento ' + e.target.tagName);
});

and you can do the same in elements, in case your code could do so:

NewImg.addEventListener('click', function(event){
    DELIMG.removeChild(NewImg);
});

which is the application of the idea that you show in

if (onclick == NewImg){DELIMG.removeChild(NewImg)}

2

Apparently what you want done is that when the image that has been added is clicked, it is deleted. That maybe it’s like in the example below:

function myFunction(src) {

  var newImg = document.createElement('img');
  newImg.className = "open";
  newImg.setAttribute('src', src);
  
  var imgOpen = document.getElementById('open');
  imgOpen.appendChild(newImg);
  
  newImg.addEventListener("click", function() {
    imgOpen.innerHTML = '';
  });
  
}
.open {
  
  width: 200px;
  height: 200px;
  
}
<li>
  <img src="https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg" onclick="myFunction(this.src)" width="100" height="100">
</li>

<div id="open"></div>

Browser other questions tagged

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