0

This works fine:

<div id='clicker' onclick='alert("clicked")'>clicker</div>
<script> $('#clicker').trigger('click'); </script>

How can I make this work ( without using eval )?

<div id='clacker' onclack='alert("clacked")'>clacker</div>
<script> $('#clacker').trigger('clack'); </script>

Trying to mimic the behavior of the inline onclick attribute, but with my own custom attribute/event, to apply a simple solution to a simple problem.

  • I see two issues with what is going on. Your inline script on the second example doesn't know what clack is, the only reason click works is because .trigger has a special case for that word. Try looking at this option instead of eval: https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string What is the use case of you 'onclack' function? If you need to call multiple functions on a click, then you can chain multiple functions in `onclick`, otherwise you can create a custom property, such as `foofunction="bar"` – Jordan Aug 04 '23 at 22:06

1 Answers1

0

You can't create custom attributes like this. Only the built-in events have corresponding on<event> attributes.

Create an event handler using jQuery .on() or JavaScript .addEventListener().

$("#clacker").on("clack", function() {
  alert('clacked');
});

$('#clacker').trigger('clack');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='clacker'>clacker</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612