Event click ignores me the first click

0

By clicking on the all button, the div content-all would be displayed. Which happens but to the second click. The code works, except that the first click that the user gives (either on the button or outside it) does not generate any action. I would like to know how to resolve this and why it happens.

function sliderButtonsClick(){
    document.getElementById('all').onclick=function(){
        document.getElementById('content-all').style.opacity=1;
    }
}

window.addEventListener("click", sliderButtonsClick);
    
asked by MarisabelGC 10.07.2017 в 16:22
source

2 answers

4

I'll explain what happens:

window.addEventListener("click", sliderButtonsClick);

When loading your page, a click listener is registered for the entire window, which will only be executed when clicking:

function sliderButtonsClick(){
    document.getElementById('all').onclick=function(){
    }
}

And I do not mean to execute the click function for the all button if you do not assign the click event to the button to listen to the next click you click on it.

That's the reason why on your first click the button does not do anything, since it still does not have any assigned events until the first click on window .

To work with your first click, what you have to do is change your function as follows:

function sliderButtonsClick(){
    document.getElementById('content-all').style.opacity=1;
}

document.getElementById('all').addEventListener("click", sliderButtonsClick);
#all{
  opacity: 1;
}

#content-all{
  opacity: 0;
}
<button id='all'>
Clic
</button>
<div id='content-all'>
Prueba
</div>

If you notice here I'm skipping the add the event on the window and do it directly on the button to avoid giving the second click for the function to run as you need it.

    
answered by 10.07.2017 в 16:37
0

One way to do this is to create your html element and assign a function to the onclick event. Here is a example .

<input type="button" id="all" onclick="sliderButtonsClick()" value="click">>
<div id="content-all" style="display:none">
<p>
Estoy en content-all
</p>
</div>

    <script>
    function sliderButtonsClick(){
        document.getElementById('content-all').style.display="block";
    }
    </script>
    
answered by 10.07.2017 в 16:37