2

Adding an event handler is pretty easy.

Now I'd like to inhibit default behavior, e.g. highlighting a text when keeping it touched for a while.

I found the preventDefault method. However I don't see how to provide the required event object to myFunction

<!DOCTYPE html>
<html>
<body>
<h1>Event Handling</h1>
<p ontouchstart="myFunction(true)" ontouchend="myFunction(false)">Touch this! </p>
<p id="demo">demo</p>

<script>
function myFunction(state) {
  document.getElementById("demo").innerHTML = (state? "Hello World": " ");
  event.preventDefault();  // how to get access to the event object ?
}
</script>

</body>
</html>

Or am I on the wrong search path?

0

2 Answers 2

4

Adding an event handler is pretty easy.

It is. But, you're doing it the 25+ year old legacy way, which should not be used today.

The event object is not automatically passed to callbacks when you use the legacy inline event attributes, such as onXyz.

Instead, use the modern approach to event handling and use .addEventListener() separately in your JavaScript. Then, the event object reference will automatically be passed as the first argument to your callback.

Now, because you want to pass your own argument to your callback, you'll need to wrap your actual callback in an anonymous function that will be the the "official" event handler and that one will receive the event argument. Then, in that wrapper, you can call your desired function and pass along the event as well as your custom argument(s).

Since not all devices support touch events, you need to check to see if they are supported by the device before you use them. Below, I've done a basic feature detection check, but read this for more comprehensive approaches.

In addition, you may also want to prevent the event from bubbling up to ancestor elements that may have event handlers registered to them as well. If so, you should also add event.stopPropagation().

Also, you should avoid .innerHTML when you can (almost always) as it has performance and security implications. Since you aren't actually getting or setting any HTML, use .textContent.

<!DOCTYPE html>
<html>
<body>
<h1>Event Handling</h1>
<p class="touch">Touch this! </p>
<p id="demo">demo</p>

<script>
  // Get your DOM references just once instead of each time your functions run
  const touchP = document.querySelector(".touch");
  const demo = document.getElementById("demo");

  // Not all devices support touch events, you should check first.
  if(touchP.touchstart){
    // The registered callback function will automatically be passed an event reference
    touchP.addEventListener("touchstart", function(event){
      // You can now call your desired function and pass the event and your argument
      myFunction(event, true); 
    });

    touchP.addEventListener("touchend", function(event){
      myFunction(event, false)
    });
  } else {
    demo.textContent = "Touch not supported on this device.";
  }

  function myFunction(event, state) {
    event.preventDefault();
    event.stopPropagation(); // If you don't want the event to bubble

    // You probably didn't want a space character returned if state == false.
    // Instead, return an empty string: ""
    demo.textContent = state ? "Hello World" : "";
  }
</script>

</body>
</html>

Sign up to request clarification or add additional context in comments.

9 Comments

You forgot some words in your statement. Should be "which I THINK should not be used today".
@kaladin_storm I did not. The use of inline event attributes causes real problems as evidenced by this question in the first place and documented in the link I shared. And, if you read that link, you would have found another that points to the documentation for inline event attributes, which states unequivocally "do not use these". This is not an opinion.
@kaladin_storm I have been coding and teaching all of this since it was invented. The popular misconception about inline event attributes is that they seem to work just fine when you start off and do simple things with them. Then, when you start writing real production code, you find that they introduce all sorts of problems. Unfortunately, they just won't go away because browsers cannot stop supporting them for legacy reasons and most newbies just copy someone else's code that uses them without actually understanding how they work (or don't work).
Definitely an opinion. If if the big guys say not to use it. Absolutely nothing wrong with an inline event.
@kaladin_storm Definitely not and in my experience (and with due respect), you opinion is one that is shared by millions of developers who haven't reached a level of coding experience to fully understand this. Just because a browser supports something, does not make it correct. This is because of the way the BOM and the DOM evolved from way back before we had standards. Inline event attributes harken back to the days of DOM level 0 (before there was a standard DOM). If you won't take the word of the actual authorities on the subject (MDN is the steward of the JavaScript language), then sorry.
|
0

You have to pass the event to your function when you call it.

<p ontouchstart="myFunction(event, true)" ontouchend="myFunction(event, false)">Touch this! </p>

function myFunction(event, state) {
  document.getElementById("demo").innerHTML = (state? "Hello World": " ");
  event.preventDefault();  // how to get access to the event object ?
}

The event exist in the event declarations.

1 Comment

Thanks, works well. (Even on my laptop with touchscreen, where Scott's solution shows "Touch not supported on this device") I've tried this (or something similar), and ran into errors that disappear now in a new test setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.