Event at mouse click

Asked

Viewed 63 times

2

I have the following script:

$(document).ready(function(){
    $('#toca').mouseenter(function(){
        $('#msg-toca').show();
    });
  $('#toca').mouseleave(function(){
        $('#msg-toca').hide();
    });
});

How do I make him change the message to mouse click? I tried with onclick and onClick, but it doesn’t work.

  • With jQuery it would just be .click(function () {}), following the same pattern used in mouseenter and mouseleave who do not possess the on

  • I tried, but it didn’t work.

  • You could show us what you did on a [mcve]?

3 answers

3


You have an event mouseenter/mouseleave to have something similar with click you have to do a toggle(), that is the first click "active" and the second click "disables"

inserir a descrição da imagem aqui

Then your code would look like this

$(document).ready(function(){
    $('#toca').click(function(){
        $('#msg-toca').toggle();
    });
});
#msg-toca {
    display: none;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<button id="toca">btn clica</button>
<div id="msg-toca">meu texto oculto</div>

    

1

If your idea would only be to swap display or hide your element using a click, what you can do is check whether it is visible or not, and hide it using is(":visible") jquery. Link with both examples.

For used would be:

$(document).ready(() => {

    $('#toca').on('click', (e) => {
      if ($('#msg-troca').is(":visible"))
        $('#msg-troca').hide();
      else
        $('#msg-troca').show();
    });
});

Now if your idea is to change the text, what you can do and define the text and check and change its content:

$(document).ready(() => {

    $('#toca').on('click', (e) => {
      if ($('#msg-troca').text() === 'Texto 2')
        $('#msg-troca').text('Texto 1');
      else
        $('#msg-troca').text('Texto 2');
    });
});

-4

Good afternoon.

Try using pure javascript without Jquery and see if it works

Go to the element inside the html form id="touches" and put onclick=" $('#msg-touches'). Hide();"

ex:

$('#msg-toca'). Hide(); is an example, recommend that in the referenced js file create a Function.

ex: Function Test(){ Alert('Click'); }

in html in div

see if it works via pure javascript

Browser other questions tagged

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