How do I refer to the value of onclick ()

2

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

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

If you'd like to see my code:

HTML5: (revealing code only)

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

Javascript: (I'm learning to report errors please)

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)}
}

For any additional information ask in the comments, sorry if there is a similar question (I could not find it).

    
asked by anonymous 15.06.2016 / 02:11

2 answers

5

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

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

In 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 like this:

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

What is the application of the idea that you show in

if (onclick == NewImg){DELIMG.removeChild(NewImg)}
    
15.06.2016 / 08:28
2

Apparently what you want done, is that when the image that was added is clicked, it is deleted. Which might be as 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>
    
15.06.2016 / 03:02