Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Malachi Dean
3,694 PointsHow can I give an HTML button CSS values and make it activate code from my JavaScript?
I'm trying to make a button that will randomize a selection from an array in JS. I have a button in CSS made up that looks decent, but I don't know how to link that CSS to a button in my HTML which then, when clicked, would activate code in my JS. Any ideas?
Jacob Mishkin
23,118 PointsAre you using Jquery, or vanilla JS?
Malachi Dean
3,694 Pointsvanilla.
1 Answer
Jacob Mishkin
23,118 PointsThere are several ways of going about this. first is this the only event handler on the page? If so you can use the onclick method like so:
document.getElementById("Button").onclick = function() {
//call random function here.
};
this should work, if not post the JS only and we'll work on it.
EDIT:
Honestly the above code is old and kinda outdated, here If you're going to do use this:
button.addEventListener("click", function() {
//randomfunction call here;
});
both styles work, but the addEventListner I think is just a better way to go.
Malachi Dean
3,694 PointsHey thanks a bunch!
Ashish Mehra
Courses Plus Student 103 PointsAshish Mehra
Courses Plus Student 103 Pointsyou can use document.getElementById(' id').style.property="value";
check out here for more http://codepen.io/mehra_as/pen/mVqMNx