Home > Back-end >  How do you toggle the click so that the function data doesn't display the second time?
How do you toggle the click so that the function data doesn't display the second time?

Time:05-21

createData is a function which displays data and appears when the button is clicked. How do I make the data disappear every other click?

document.getElementById("clickme").onclick = createData;

CodePudding user response:

let item = document.getElementById("clickme")
let checker = true;

item.addEventListener('click', checkData);


function checkData() {
  if (checker) {
    createData();
  } else {
    clearData();
  }
}

function createData() {
    checker = false;
    console.log('create')
}
function clearData() {
    checker = true;
    console.log('clear')
}
<button id="clickme">
  click me!
</button>

CodePudding user response:

There are a number of ways to do this but the simplest would be to just toggle the display state of the data. Also, don't use inline event attributes, like onclick as this is a 25 year old legacy technique for setting up events that is way out of date today and can cause all sorts of issues with your code. Instead, use .addEventListener(), which is the modern standards-based way to set up events.

document.getElementById("clickme").addEventListener("click", createData);

const data = document.querySelector(".data");
function createData(){
  data.classList.toggle("hidden");
}
.hidden { display:none; }
<div id="clickme">Click to toggle display of data</div>
<div >This is the data</div>

CodePudding user response:

Ok... If I got it right, you want any other click to destroy the previously data from createData, is it right?

Since I can't see the createData, I'll assume it is a function as bellow:

//your function assumed
function createData(){
  //creating data

  return data
}

if you want createData to return data whenever you click over $('#clickme') and destroy whenever you click something else, try as bellow:

$('#clickme').on('click',function(){
  
})

$(document).on('click',function(e){
  youClickedThisId = e.target.id 
  if (youClickedThisId == 'clickme') {
    createData()
    console.log(createData())
  } else {
    //createData( with Parameters to destroy ) or
    //a new function to destroy previously data called: destroyData() 
    console.log(destroyData())
  }
})

let data = 'i`m your data'

function createData() {
  return data
}

function destroyData() {
  data = 'i was your data'
  data = null //or data = ''
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<button id="clickme"> CLICK ME </button>
</body>

On next questions, I advice to show your code! Hope this answer helps you out!

  • Related