1

I want to get the returned value of a clicked button, and then use it to make an if statement. All the answers that I read here about people trying to do that are either very old using old script that doesn't work anymore, or not the same case.

function remove() {
  if (document.getElementById("removing").value == true) {

    document.getElementById("test").style.backgroundColor = "red";
  }
}
<div id="test">test</div>
<button id="removing" onclick="remove()">Remove a word</button>

I have tried using the value property, and onclick, but non of them equal true when the button is clicked.

I tried using alert to display the value, but it displays nothing.

Does clicking a button actually returns a value, and if so, what is it?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
happy_story
  • 1
  • 1
  • 7
  • 17
  • 1
    No, clicking a button does not return a value. In general, **events** don't "return" any value. They just happen and you can register event handlers to be executed when they happen. The fact that `remove` is executed means that the button was clicked. – Felix Kling Jan 28 '21 at 13:49
  • I see. So, how do I do that? How do I use an executed event in an if statement? – happy_story Jan 28 '21 at 14:23
  • I don't understand why you need an `if` statement? Where do you want to know that the button was clicked? Please provide more context. In your example, the fact that `remove` is called already means that the button is clicked. – Felix Kling Jan 28 '21 at 14:31
  • @FelixKling ... Since one could invoke such a handler function from anywhere just like this ... `remove()` ... I assume the OP just wants to be sure about the handler being invoked from within an event handling process. – Peter Seliger Jan 28 '21 at 17:19
  • 1
    @PeterSeliger: Possibly. But it can only be helpful for the OP to clarify :) – Felix Kling Jan 28 '21 at 18:44
  • 1
    Sorry I haven't responded yet. I read all the answers here, but I am trying to assimilate and make sense of a lot of information right now. I am testing and experimenting a whole bunch of stuff right now. Given that I'm very new to JS, some of the stuff that I keep seeing don't make sense to me, and I am trying to make sense of it, and formulate some key questions so I can ask you guys while I have the opportunity. Please give me some time before I can formulate my questions in a more proper way. – happy_story Jan 28 '21 at 18:47
  • Hey. So, I don't have any other additional questions to my original question, but I do want to ask you guys about something a bit unrelated. When you convert a string into an array, and then use splice to remove array items from it by clicking a button, but instead of setting the exact item to be removed, you use counter++ instead, now, why is it that, if I remove an item and then replace it with another one, the counter incrementation works as expected. For each occurrence it increases with 1, but if I choose not to replace an item, just remove it, the incrementation increases with 2. Why? – happy_story Jan 29 '21 at 11:38
  • Here's a jsfiddle for demonstration: https://jsfiddle.net/z8gu4bm2/ – happy_story Jan 29 '21 at 11:38
  • @Ihatecontrolfreaks ... the additional question most probably will not be answered unless it was ask as (or in a) separate thread. – Peter Seliger Jan 29 '21 at 16:47
  • @PeterSeliger I thought it was a simple 1 sentence answer, that's why I didn't want to make a new thread for it, but it's fine. No worries. – happy_story Jan 29 '21 at 18:56

3 Answers3

2

DOM Events are handled by an EventListener's callback function.

Thus such a handler function, if triggered by an event and forwarded by an event listener's handleEvent method, always will be invoked with an event object as this function's single argument.

All information related to this event are carried by the event itself. Its properties can be read and some even can be written/changed.

It is obvious from the provided example that the OP wants to assure that an event handler has been triggered by just a specific html element. Thus any valid approach just needs to look into the event's currentTarget property ...

// the way the OP might want to handle the problem.
function handleRemoveWord(evt) {
  const elmNode = evt.currentTarget;

  // make sure the handler was
  // triggered by the intended element ...
  // ... here by comparing node properties.
  if (
    (elmNode.tagName.toUpperCase() === 'BUTTON')
    && (elmNode.id === 'remove')
  ) {
    document
      .getElementById('test')
      .style.backgroundColor = 'red';
  }
}

// another way the OP might want to handle the problem.
function handleRemoveAnotherWord(evt) {

  // `this` referres to the element which got
  // bound to the handler via `addEventListener`.
  const targetNode = this;

  // make sure the handler was
  // triggered by the intended element ...
  // ... here by comparing node references.
  if (targetNode === evt.currentTarget) {
    document
      .getElementById('test')
      .style.backgroundColor = 'cyan';
  }
}

// an alternative way of solving the problem
// of always being assured about the correct
// element having triggering the event handling.
function handleRestoreWordWithBoundContext(evt) {
  const context = this;
  const { elmTest, elmRestore } = context;

  // make sure the handler was
  // triggered by the intended element ...
  // ... here by comparing node references.
  if (elmRestore === evt.currentTarget) {

    elmTest.style.backgroundColor = '';
  }
}


function initialize() {
  // the way(s) the OP might want to handle the problem.
  document
    .getElementById('remove')
    .addEventListener('click', handleRemoveWord);

  document
    .querySelector('#removeAnother')
    .addEventListener('click', handleRemoveAnotherWord);

  // an alternative way of soving the problem
  // of always being assured about the correct
  // element having triggering the event handling.
  const elmTest = document.querySelector('#test');
  const elmRestore = document.querySelector('#restore');

  elmRestore.addEventListener(
    'click',
    handleRestoreWordWithBoundContext.bind({
      elmTest, 
      elmRestore,
    })
  );
}
initialize();
<div id="test">test</div>

<button id="remove">Remove a word</button>
<button id="removeAnother">Remove another word</button>
<button id="restore">Restore a word</button>

As one might have noticed, the example features a third button with yet another way of implementing an event handler. This additional handler assumes its this context to carry additional information. This is possible by invoking bind on this handler function and providing exactly the information one wants to be present as the event handlers this context. Every time this function specific method is invoked it creates another function which does have access to the bound information via the this keyword.

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
1

Dispatching Javascript event handlers always returns true, even if it returns false, which we all know is used to prevent default behaviour of an event. We don't usually use the return values of Event handlers or even return anything for that matter.

In your case, I think you're trying to acess the value of the currentTarget element(the button 'removing' in your case). For this you can use the event object, which gets passed on as parameter to your event handler.

event.currentTarget is a way of referencing the element on which an event is being dispatched(triggered) on. It's just like using 'this' inside the event handler, except it also works on arrow functions.

So do something like this:

function remove(event) {
  let button = event.currentTarget;
  if (buttton.value) {
   document.getElementById("test").style.backgroundColor ="red";
  }
}

and in HTML,

<div id="test">test</div>
<button id="removing" onclick="remove(event)">Remove a word</button>

Notice I've used remove(event).

Edit Based on comment below: Using onclick will require you to create you a global 'remove' function. If you do, '...onclick="remove(event)" what it basically does is creates the function below, a wrapper basically:

// In the global scope
[reference element].onclick = ()  => {
  remove(event);
}

So you must have a global 'remove' function. So this won't work in modules cause each modules have their own top level scope. And you're gonna wanna have to use modules if you plan to work on sophisticated projects.

NOTE Using inline 'onclick' attributes in html has following disadvantages on heavy requests from a comment below:

-separation of concern : You usually don't want to mix up your UI logic(what happens on clicking a button) with presentation. You want a clear split between content, style and script.

-only one handler can be assigned using onclick.

-if an event is specified inline, the JS is specified as a string (attribute values are always strings) and evaluated when the event fires.(extra wrapper code builds internally).

-as I've mentioned before, you are faced with having to reference named functions. This is not ideal and has implications on the function needing to be global which will really bite you back when you use modules.

In short, handle events centrally via the dedicated addEventListener API.

Nike Lepz
  • 485
  • 2
  • 12
  • Please do not use ´event´ as global *out of the blue* variable as it is practiced by the given examples inline style ... ` – Peter Seliger Jan 28 '21 at 14:21
  • @PeterSeliger what do you think of the edit above. I'm new to programming and could really use opinion in general. Thanks in advance. – Nike Lepz Jan 28 '21 at 14:34
  • but isn't event always available like that. It's not like we need to import it from somewhere is it? Or am I missing something? Because you're soooooo OP. – Nike Lepz Jan 28 '21 at 15:12
  • Making use of inline event handling and the global `event` object is considered harmful and thus bad practice. – Peter Seliger Jan 28 '21 at 18:53
  • @Peter Seliger care to explain as to why it is considered harmful. – Nike Lepz Jan 28 '21 at 19:01
  • The first highest ranked answers of ... [Why are inline event handler attributes a bad idea ...](https://stackoverflow.com/questions/11737873/why-are-inline-event-handler-attributes-a-bad-idea-in-modern-semantic-html) ... in addition [Inline event handlers — don't use these](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) ... and [Disadvantages of using HTML event handler attributes](https://www.javascripttutorial.net/javascript-dom/handling-events-in-javascript/) – Peter Seliger Jan 28 '21 at 20:16
1

Simply change background color onClick of button as:

function remove() {
  document.getElementById("test").style.backgroundColor = "red";
}
<div id="test">test</div>
<button id="removing" onclick="remove()">Remove a word</button>
  • I think what the OP tries to tackle is not the above shown basic kind of event handling. The OP is looking for an approach which assures a certain element being the trigger of an event or the event's current target. – Peter Seliger Jan 28 '21 at 16:32