1

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;
Brian
  • 87
  • 1
  • 5

4 Answers4

1

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>
VladykoD
  • 284
  • 2
  • 8
0

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!

-1

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(){
  // You can have more code in here that updates the data as needed before
  // toggling its display state
  data.classList.toggle("hidden");
}
.hidden { display:none; }
<div id="clickme">Click to toggle display of data</div>
<div class="data hidden">This is the data</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

It's tough to make a strong recommendation without more context, but here is a relatively simple solution if you are comfortable with the state management living inside the actual element. I think VladykoD's anser is probably safer.

Here I am adding an attribute to the element with a value of the attribute being zero. When the user clicks the element, the checkClickIterationAndCreateData function will fire, grab the click_monitor attribute, parse that as an integer, check to see if that integer is even or odd, and then add +1 to the click_monitor.

function addCreateDataFunction(elm_id){
    let target_elm = document.getElementById(elm_id);
    target_elm.setAttribute('click_monitor','0');
    target_elm.onclick = checkClickIterationAndCreateData;
}
function checkClickIterationAndCreateData(){
    let click_iteration = parseInt(this.getAttribute('click_monitor'));
    this.setAttribute('click_monitor',click_iteration + 1);
    if(click_iteration % 2 == 0) createData();
    else console.log('do nothing');
}
function createData(){
    console.log('creating data')
}
addCreateDataFunction('clickme')
Andre Bradshaw
  • 119
  • 1
  • 5
  • You can't just make up custom attributes in HTML. That results in invalid markup. You can however create a [`data-*` attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes), but that (and the use of `setAttribute()`) is way overkill. you can just access an attribute through a JavaScript property (i.e. element.attributeName = someValue). – Scott Marcus May 20 '22 at 17:25
  • [You should also not be using event attributes like `onclick`](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991) and instead be using [`.addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). – Scott Marcus May 20 '22 at 17:27
  • What one "can" do and what is advisable given context are two different things. One absolutely can make up custom attributes in HTML. It is also true that one should probably not use onclick unless they are explicitly looking to override a click listener, but again -- the context of the need matters. – Andre Bradshaw May 20 '22 at 17:38
  • **Uh no.** Custom HTML is invalid HTML, period. The entire reason `data-*` attributes were adopted as standard in HTML5 was to give developers a valid way to do what you are suggesting. Don't reinvent the wheel with a non-standard approach. And inline event properties don't give you any ability to override an event listener that `.addEventListener()` doesn't give you. In fact, the entire point of `addEventListener()` is that is provides a more robust event registration/deregistration mechanism than event properties. – Scott Marcus May 20 '22 at 17:44
  • But I do agree with you... *What one "can" do and what is advisable given context are two different things.* <-- Just because you *can* use your approach, doesn't make it advisable... for many reasons. – Scott Marcus May 20 '22 at 17:44
  • Yes. Which is why I stated in my original response that someone else's answer was safer. It is good for you to point these things out. I did not know there was an issue with the attribute method I was using because I CAN in fact do it -- I do it all of the time. – Andre Bradshaw May 20 '22 at 17:47
  • I've been a professional corporate IT trainer for 30 years and have been coding in HTML, CSS and JavaScript since each was invented. The single biggest problem with code being produced today is that current developers don't understand the evolution of these languages, the "browser wars" that predated them and how standards evolved because of it (cont)... – Scott Marcus May 20 '22 at 17:51
  • ...Today people just copy/paste someone else's code that seems "to work" just fine without learning and understanding what that code does and where it came from. So much ancient code will "work" today simply for backwards compatibility. The `font` element still "works", but it's wrong to use it because it goes against the modern separation of concerns methodology of web development. It doesn't matter if someone "does it all the time". It doesn't make it correct to do it. – Scott Marcus May 20 '22 at 17:51
  • I understand. I am sure that is frustrating. Perhaps consider your wording in addressing people's use of improper or sub-optimal methods. Saying someone cannot do something or that it is wrong to do something when the person has been doing it successfully may not be an optimal approach for pushing people to use better methods. It's easy for someone to dismiss a comment/recommendation if it does not comport with an individual's lived experience. – Andre Bradshaw May 20 '22 at 17:55
  • I never said you couldn't *do* it, but yes, I did say it was wrong. Because it is. And until the web development community speaks with one voice loudly about these practices, they will continue. It's not 1998 any more. Stop using (and more importantly) and advocating for this type of code. `Code that "works" !== Correct Code` and never has in any programming language. – Scott Marcus May 20 '22 at 17:59
  • You absolutely said, "you can't." Read your comment. Preach your message. I do not entirely disagree with it, but correct != your_opinion. There is optimal and sub-optimal in a given context. – Andre Bradshaw May 20 '22 at 18:07
  • None of what I've said is opinion. There are real world implications for using legacy code that you've shown. That's entirely my point. If you aren't educated enough in these nuances, you may think "it works so it's good" when there are real reasons why it works, but it's bad. And yes, I did say "you can't". My mistake, I should have said "It's invalid". I mean you *can* play in traffic, but you definitely shouldn't. – Scott Marcus May 20 '22 at 18:09