I want to call js function on client side when I click button/div elements.
This scenario works.(addEventListener)
MyComponent.js
import Script from 'next/script'
export default function MyComponent({ props }) {
return (
<>
<div className="slider-buttons">
<div key="1" data-id="1" className="slider-button active"></div>
<div key="2" data-id="2" className="slider-button"></div>
<div key="3" data-id="3" className="slider-button"></div>
<div key="4" data-id="4" className="slider-button"></div>
</div>
<Script src="/assets/slider.js" strategy="afterInteractive" />
</>
)
}
Slider.js
var elements = document.getElementsByClassName("slider-button");
Array.from(elements).forEach(function (element) {
element.addEventListener('click', ClientClick);
});
function ClientClick(e) {
if (e && e.target) {
var clickedId = e.target.getAttribute('data-id');
// DOM Manipulation
}
}
This scenario I want (without addEventListener)
MyComponent.js
import Script from 'next/script'
export default function MyComponent({ props }) {
return (
<>
<div className="slider-buttons">
<div key="1" data-id="1" onClick="ClientClick(1)" className="slider-button active"></div>
<div key="2" data-id="2" onClick="ClientClick(2)" className="slider-button"></div>
<div key="3" data-id="3" onClick="ClientClick(3)" className="slider-button"></div>
<div key="4" data-id="4" onClick="ClientClick(4)" className="slider-button"></div>
</div>
<Script src="/assets/slider.js" strategy="afterInteractive" />
</>
)
}
Slider.js
function ClientClick(clickedId ) {
// DOM Manipulation
}
Returns an error
Unhandled Runtime Error Error: Expected
onClicklistener to be a function, instead got a value ofstringtype.
Is that possible to call JS function on client-side without addEventListener?