Javascript div onclick this

onclick Event

The onclick event occurs when the user clicks on an HTML element.

Mouse Events

Event Occurs When
onclick The user clicks on an element
oncontextmenu The user right-clicks on an element
ondblclick The user double-clicks on an element
onmousedown A mouse button is pressed over an element
onmouseenter The pointer is moved onto an element
onmouseleave The pointer is moved out of an element
onmousemove The pointer is moving over an element
onmouseout The mouse pointer moves out of an element
onmouseover The mouse pointer is moved over an element
onmouseup The mouse button is released over an element

See Also:

Tutorial:

Syntax

In JavaScript, using the addEventListener() method:

Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: MouseEvent
Supported
HTML tags:
All exept: , ,
, , , , , , , , and

More Examples

Click a to display the date:

Click a element to change the text color:

Click me to change my color.

Another example on how to change the color of an element:

Click me to change my color.

Click to copy text from one input field to another:

function myFunction() document.getElementById(«field2»).value = document.getElementById(«field1»).value;
>

How to assign an «onclick» event to the window object:

function myFunction() document.getElementsByTagName(«BODY»)[0].style.backgroundColor = «yellow»;
>

Use onclick to create a dropdown:

function myFunction() document.getElementById(«myDropdown»).classList.toggle(«show»);
>

Browser Support

onclick is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Make a Div Clickable Using JavaScript

Make a Div Clickable Using JavaScript

  1. Using the onclick Event Handler to Make a Div Clickable
  2. Adding a Conditional Click to a Div
  3. Good to Have Feature in a Clickable Div
  4. Achieving Anchor Element Functionality With a Clickable Div

Using the onclick Event Handler to Make a Div Clickable

The anchor element is a displayed inline. And this feature may not always work in our favour while designing the Graphical User Interface. div s are easy to use while designing GUIs as they are stand-alone block elements. A div is a content division element and is not clickable by default. We may have to use the onclick event handler to process the events emitted by the element when a user clicks on it. The onclick event handler accepts a function or a JavaScript expression preceding the function. When a user clicks on the div , javascript executes the associated functions or the expressions at the run time. There are a couple of ways to add the onclick event handler to a div element.

Using Both HTML and JavaScript Code Combined to Make a Div Clickable

The most widely used approach in javascript and various frameworks of javascript is to link a function call to the onclick event handler in the HTML code. Then we write the function definition associated with it in the javascript code. Once a user clicks the div , the onclick event handler will execute the function passed as an argument to the onclick of the div element. Refer to the following code.

div id="title-div" onclick="sayHello()">div> 
function sayHello()   console.log("Hello there !!"); > 

Once the user clicks the title-div , the associate function sayHello() gets executed. And we will have Hello there !! logged in the web console. This approach is widely used and makes it easy to debug as compared to the pure javascript approach. The HTML explicitly shows the binding.

Using Pure JavaScript to Make a div Clickable

Another approach is purely javascript based. We first find the intended HTML element using any of the methods like document.getElementById() , document.getElementsByClassName() , document.querySelectorAll() etc. The most commonly used method to find the HTML element is the document.getElementById() as it uniquely identifies the HTML elemnt based on the id we assign to it in the HTML. Once we find the element, the div element, we attach the onclick event handler and link the function to be executed on click of the div . The following code elleborates the approach.

div id="title-div">Click herediv> 
window.onload = function ()   var el = document.getElementById("title-div");  el.onclick = sayHello; >  function sayHello()   console.log("Hello"); > 

In the above code, we bind the onclick event handler purely in JavaScript. There is no trace of any onclick mapping in the HTML. The HTML is kept simple with a div element and an associated id . Also, note that we assign the sayHello function object to the onclick event handler. If we link sayHello() (with parenthesis) instead of sayHello , it will cause the JavaScript to execute the function on the window load itself. And nothing will happen when a user clicks on the div element.

Adding a Conditional Click to a Div

We can trigger the click event conditionally. Using HTML and JavaScript approach, we can add expression coupled with the && or the || sign based on the requirement. JavaScript executes the click event based on how the boolean expression evaluates. If it evaluates to true, JavaScript executes the associated function.

div onclick="isEvenClick() && sayHello()">Click Here . div> 
function sayHello()   console.log("Hello"); >  function isEvenClick()   clickCounter++;  return (clickCounter % 2 === 0) > 

The above code will log Hello only on an even number of clicks. We can also write the same code with expression instead of the isEvenClick() function as elaborated in the following code.

div onclick="(++clickCounter % 2 === 0) && sayHello()" id="title-div">Click herediv> 

The expression is evaluated at run time for the value of clickCounter . If the clickCounter is even, the expression (++clickCounter % 2 === 0) evaluates to true and the sayHello() function gets executed.

Good to Have Feature in a Clickable Div

Once we add a click listener to a div , it will still be a div . The user will not understand whether that HTML element has any user interaction associated with it. For that purpose, we can add features using the CSS styles. One such thing is to make the cursor a hand icon. We can do it by using cursor: pointer . It is a good UI/UX practice to hint to the end-user that this HTML element is actionable. We can do it in the following way.

div onclick="sayHello()" style="cursor: pointer;">Click Here . div> 

We can achieve the same using pure JavaScript by adding styles to the element at run time. We first select the element using document.getElementById() and then add the cursor style using el.style.cursor and assign it the string value pointer . The following code explains it.

div onclick="sayHello()">Click Here . div> 
window.onload = function ()   var el = document.getElementById("title-div");  el.style.cursor = "pointer";  el.onclick = sayHello; >  function sayHello()   console.log("Hello"); > 

Achieving Anchor Element Functionality With a Clickable Div

div onclick="navToGoogle()" style="cursor: pointer;">Take me to Googlediv> 
function navToGoogle()   window.location.href = "https://www.google.com"; > 

Источник

JavaScript — How to show and hide div by a button click

To display or hide a by a click, you can add the onclick event listener to the element.

The onclick listener for the button will have a function that will change the display attribute of the from the default value (which is block ) to none .

For example, suppose you have an HTML element as follows:

The element above is created to hide or show the element on click.

You need to add the onclick event listener to the element like this:


When you click the element again, the display attribute will be set back to block , so the will be rendered back in the HTML page.

Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.

You can add the JavaScript code to your HTML tag using the tag as follows:

Feel free to use and modify the code above in your project.

I hope this tutorial has been useful for you. 👍

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Читайте также:  Php add variable to variable
Оцените статью