Javascript add onclick to element

Как добавить onclick к кнопке через js

Свойство onclick у элемента отвечает за обработку события клика по элементу. Чтобы добавить обработчик, достаточно просто присвоить этому свойству функцию, которая вызовется при клике:

// Получаем элемент const element = document.getElementById('test'); // Добавляем обработку события element.onclick = (event) =>  // . console.log(event); >; 

Этот способ имеет недостаток: нельзя навешать несколько обработчиков-функций на событие.

// Получаем элемент const element = document.getElementById('test'); // Добавляем обработку события element.onclick = (event) =>  // . console.log('first handler'); >; // Добавляем второй обработчик element.onclick = (event) =>  // . console.log('second handler'); >; 

Первый обработчик перезапишется вторым. Чтобы этого избежать, лучше использовать addEventListener() :

// Получаем элемент const element = document.getElementById('test'); // Добавляем обработку события element.addEventListener('click', (event) =>  // . console.log('first handler'); >); // Добавляем второй обработчик element.addEventListener('click', (event) =>  // . console.log('second handler'); >); 

В таком случае оба обработчика будут срабатывать по клику на элементе.

Источник

Javascript add onclick to element

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Create an element with onClick event listener using JS

To create an element with an onClick event listener:

  1. Use the document.createElement() method to create the element.
  2. Use the addEventListener() method to add a click event listener to the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
// ✅ Create element const el = document.createElement('div'); el.addEventListener('click', function handleClick(event) console.log('element clicked 🎉🎉🎉', event); >); // ✅ Add text content to the element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `Hello world`; el.style.backgroundColor = 'salmon'; el.style.width = '150px'; el.style.height = '150px'; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

We used the document.createElement method to create the element.

Copied!
const el = document.createElement('div');

The only parameter we passed to the method is the type of element to be created ( div in the example).

The createElement method returns the newly created element.

We called the addEventListener method on the element, passing it the following 2 parameters:

  1. The event type to listen for ( click in the example).
  2. A function that gets invoked when the event is triggered.
Copied!
const el = document.createElement('div'); el.addEventListener('click', function handleClick(event) console.log('element clicked 🎉🎉🎉', event); >);

You can use the textContent property to set the element’s text content or the innerHTML property to set the element’s inner HTML markup.

Copied!
// ✅ Create element const el = document.createElement('div'); el.addEventListener('click', function handleClick(event) console.log('element clicked 🎉🎉🎉', event); >); // ✅ Add text content to the element el.textContent = 'bobby hadz tutorial'; // ✅ Or set the innerHTML of the element // el.innerHTML = `Hello world`;

You shouldn’t use the innerHTML property with user-provided data without escaping it. This would leave your application open to cross-site scripting attacks.

You can use the appendChild method to add the element to the page.

Copied!
// ✅ Create element const el = document.createElement('div'); el.addEventListener('click', function handleClick(event) console.log('element clicked 🎉🎉🎉', event); >); // ✅ Add text content to the element el.textContent = 'Hello world'; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

The method adds a node to the end of the list of children of the element it was called on.

# Create an element with onClick event listener using onclick

You can also use the onclick attribute to add an event lister after creating the element.

Copied!
// ✅ Create element const el = document.createElement('div'); el.onclick = function handleClick(event) console.log('element clicked 🎉🎉🎉', event); >; // ✅ Add text content to the element el.textContent = 'bobby hadz tutorial'; // ✅ Or set the innerHTML of the element // el.innerHTML = `Hello world`; el.style.backgroundColor = 'salmon'; el.style.width = '150px'; el.style.height = '150px'; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

The onclick attribute specifies a function to run when the element is clicked.

Either approach works, but the addEventListener method is more commonly used.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript DOM Events: Onclick and Onload

JavaScript DOM Events: Onclick and Onload

In the early days of the internet, web pages were truly static – there were only text and images. Sure, sometimes that image was an animated gif, but it was still just an image.

With the advent of JavaScript, it became increasingly possible to create interactive pages that would respond to actions like clicking on a button or having a scroll animation.

There are a number of DOM (Document Object Model) events that you can listen for in JavaScript, but onclick and onload are among the most common.

Onclick Event

The onclick event in JavaScript lets you execute a function when an element is clicked.

Example

 function myFunction() 

In the simple example above, when a user clicks on the button they will see an alert in their browser showing Button was clicked! .

Adding onclick dynamically

The example above works, but is generally considered bad practice. Instead, it’s better to separate the content of the page (HTML) from the logic (JS).

To do this, the onclick event can be programmatically added to any element using the following code in the following example:

click on this element.

const p = document.getElementById("foo"); // Find the paragraph element in the page p.onclick = showAlert; // Add onclick function to element function showAlert(event)

Note

It’s important to note that using onclick we can add just one listener function. If you want to add more, just use addEventListener() , which is the preferred way for adding events.

In the above example, when a user clicks on the paragraph element in the html , they will see an alert showing onclick Event triggered .

Preventing default action

However if we attach onclick to links (HTML’s a tag) we might want prevent default action to occur:

Guides const link = document.getElementById("bar"); // Find the link element link.onclick = myAlert; // Add onclick function to element function myAlert(event) 

In the above example we prevented default behavior of a element (opening link) using event.preventDefault() inside our onclick callback function.

Onload Event

The onload event is used to execute a JavaScript function immediately after a page has been loaded.

Example:

const body = document.body; body.onload = myFunction; function myFunction()

Which can be shortened to:

document.body.onload = function()

In the above example, as soon as the web page has loaded, the myFunction function will be called, showing the Page finished loading alert to the user.

The onload event is usually attached to the element. Then once the of the page has loaded, which includes all images, and CSS and JS files, your script will run.

More Information:

These are only two of the many DOM events you can manipulate with JavaScript, but are among the mostly commonly used.

But sometimes you don’t need to listen for DOM events at all, and want to use a time based event like a countdown. For a quick tutorial on timing events, check out this article.

Источник

Читайте также:  Width and height equal css
Оцените статью