Home > Enterprise >  when i click a button second time my label want to dissappear
when i click a button second time my label want to dissappear

Time:09-18

i have a button and label like this:

<button id="btn">Button</button>
<label  id="lbl">lbl</label>

When i click this button second time that label want to hide/dissappear

CodePudding user response:

You can use the onclick event of the button. Add JQuery and use the below code.

var cnt = 0;
$('#btn').on('click', function() {
  cnt  ;
  if(cnt == 2)
    $('#lbl').hide();
})

OR, in vanilla js you can use

var cnt = 0;
document.getElementById('btn').onclick = function() {
  cnt  ;
  if(cnt == 2)
    document.getElementById('lbl').style.display = 'none';
};

CodePudding user response:

Code :

button = document.getElementById("btn")
label = document.getElementById("lbl")

button.addEventListener('dblclick', function(){
  label.style.display = 'none';
})
<button id="btn">Button</button>
<label  id="lbl">lbl</label>

CodePudding user response:

SOLUTION

Use Inbuilt JS event

There is event in JS ondblclick event which fires only on double clicked check the snippet below

function hide() {
  document.querySelector("label").style.display= "none";
}
<button  ondblclick="hide()" id="btn">Button</button>
<label  id="lbl">Hide me after Double clicking on button</label>

CodePudding user response:

The code you provided not hide or dissappear

There is a chance of your'e code is being overwrited by other css.

CodePudding user response:

It's divided to 3 steps:

  1. Set the counter to count the clicks.
  2. Add the click listener on button and increment the counter by 1 on click.
  3. If the counter reaches 2, modify the CSS of label with display: none to make it disappear

Here's the pure Javascript solution:

var lbl = document.getElementById('lbl');
var btn = document.getElementById('btn');
var clicks = 0;

btn.addEventListener('click', (e) => {
  clicks  ;
  if (clicks === 2) lbl.style.display = 'none';
});
<button id="btn">Button</button>
<label  id="lbl">lbl</label>

CodePudding user response:

Try this.

let count = 0
const btn =   document.getElementById("btn");
   btn.onclick = function () {
            count  ;
       if(count === 2){
        document.querySelector("label").style.display= "none";
       }
        }
<button id="btn">Button</button>
<label  id="lbl">lbl</label>

CodePudding user response:

Keep a count of the number of times the button has been clicked and when it reaches 2 make the lbl display none.

This snippet adds an event listener to the label to achieve this.

let count = 0;
const btn = document.querySelector('#btn');
const lbl = document.querySelector('#lbl');
btn.addEventListener('click', function() {
  count  ;
  if (count == 2) {
    lbl.style.display = 'none';
  }
});
<button id="btn">Button</button>
<label id="lbl">lbl</label>

  • Related