Javascript program for onclick event




















Our selector, article. This means that any time the article element has a class of open attached to it, the maximum height will change from px to px to show the rest of the article. This is possible with JavaScript — our game changer. We styled our button with a darkish background and made it white. Finally, we used the hover pseudo-class in CSS to change the button cursor to a pointer.

The background color slightly changes when a user hovers their cursor over it. The next thing we need to do is to write our JavaScript so we can see the rest of the article that is hidden. We have an onclick attribute inside our button opening tag ready to execute a showMore function, so let's write the function. The next thing we need to do is write the function showMore so we can toggle between seeing the rest of the article and hiding it.

We use an if…else statement here. This is a crucial part of JavaScript that helps you make decisions in your code if a certain condition is met. Here, if the class name of the article equals open that is, we want to add the class of open to it, which was set to a maximum height of px in the CSS , then we want to see the rest of the article.

Else, we want the article to return to the initial state where a part of it is hidden. We do this by assigning it a class of open in the else block, which makes it show the rest of the article. Then we set the class to an empty string none in the if block, which makes it return to the initial state.

Our code is working fine with a smooth transition:. I hope this tutorial helps you understand how the click event works in JavaScript. We explored two different methods here, so now you can start using them in your coding projects. If you read this far, tweet to the author to show them you care.

Tweet a thanks. Mouse Events Change the color of an element when the cursor moves over it. We just launched W3Schools videos. Get certified by completing a course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:.

Mouse Over Me. Click Me. This HTML element is generally a button but it can be also ahead, iframe, label element, etc. We will start with a very popular example where we will call an already defined function with the onClick event. We will just provide the function name to the onClick event. This code can be a single statement or multiple statements. Free certificates of completion Focused on data science skills Flexible learning timetable.

Example Copy. Try it Live Learn on Udacity. Previous Topic Next Topic. JavaScript CheatSheets of Functions. JavaScript Syntax. Array Functions. Read review.



0コメント

  • 1000 / 1000