Hello everyone
I know this is very easy to do but i’ve been struggling for a while to do it.
I’ve developed a custom component (button)
Here’s the content of the buttonsearch.html
I want to add the function onclick on the button but when I do it the console doesn’t print anything…
Here’s the content of my js in clientlibs
When I click on the button I don’t get the message printed in the console ?
Anyone knows how can I print the message to the console when the button is clicked ?
Thanks in advance.
Solved! Go to Solution.
Views
Replies
Total Likes
This should work:
document.querySelector('.header__search').addEventListener('click', () => { alert('hi') });
Hi @odabio
You can simply try like this:
1. Add on click event in the client lib JS file
Eg: test.js
function myFunction() {
console.log("You clicked me");
}
2 . Include the clientlib in component level so that you can call Java script function upon onclick.
Example:
<head data-sly-use.clientLib="${'/libs/granite/sightly/templates/clientlib.html'}">
<!--/* for css+js */-->
<meta data-sly-call="${clientLib.all @ categories='site.core.test'}" data-sly-unwrap></meta>
</head>
<sly>
<button type="button" onclick="myFunction()"> <span> Search</span></button>
</sly>
Hope this helps you .
Thanks
Hi @odabio, in general your code looks correct. I was able to run it successfully on my local instance. Please keep in mind one thing, as this could be the reason why you're not seeing message printed in the console.
Your code is looking for first element with class header__search, if for any reason you will have multiple elements with this class, onclick event will be registered for the first one only. But the first one not always needs to mean the one user is clicking.
In other words please check in the page markup if you have only one element with class header__search, if not this could be the reason of your issue - onclick event could be registered on different element that you are expecting. You can also temporarily try to change you class name to something unique to confirm that you are able to run your code correctly.
Alternatively you can use below jQuery code that will register onclick event on all elements with class header__search.
$(".header__search").click(function() { console.log("Clicked"); })
Please check https://codepen.io/arunpatidar02/pen/yLoqrYv if helps
Try using
document.queryselector
instead of getElemetByClassName
This should work:
document.querySelector('.header__search').addEventListener('click', () => { alert('hi') });
Views
Likes
Replies