Set target in javascript

Anchor target Property

Change the target of a link to «_blank» (the link will be opened in a new window):

Description

The target property sets or returns the value of the target attribute of a link.

The target attribute specifies where to open the linked document.

Browser Support

Syntax

Return the target property:

Property Values

Value Description
_blank Opens the linked document in a new window
_self Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frameset
_top Opens the linked document in the full body of the window
framename Opens the linked document in a named frame

Technical Details

More Examples

Example

Return the value of the target attribute of a link:

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.

Источник

Event.target

Свойство target интерфейса Event является ссылкой на объект, который был инициатором события. Он отличается от Event.currentTarget , если обработчик события вызывается во время всплытия (bubbling) или захвата события.

Пример

Свойство event.target может быть использовано для реализации делегирования событий.

    в этом контексте e.target.style.visibility = ‘hidden’; > // Назначим обработчик к списку // Он будет вызван когда кликнут на любой
    ul.addEventListener(‘click’, hide, false);

Спецификации

Поддержка браузеров

BCD tables only load in the browser

Примечания

В IE 6-8 модель событий отличается. Обработчики событий назначаются с помощью нестандартного EventTarget.attachEvent (en-US) метода. При этом в объекте события есть свойство Event.srcElement , вместо target свойства, но по смыслу оно идентично event.target .

function hide(e)  // Поддержка IE 6-8 var target = e.target || e.srcElement; target.style.visibility = 'hidden'; > 

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

target Event Property

Get the name of the element where the event occurred:

Description

The target property returns the element where the event occured.

The target property is read-only.

The target property returns the element on which the event occurred, opposed to the currentTarget property, which returns the element whose event listener triggered the event.

See Also:

Syntax

Technical Details

More examples

Example

Get the element that triggered the event:

Example

Get the name of the element that triggered the event:

Browser Support

event.target 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.

Источник

Understanding event.target and Use Cases

Blog Cover

Profile picture

The Event interface represents an event that takes place in the Document Object Model [DOM].

Events refer to happenings in the DOM from the loading of a page to the navigation to another page or the closing of a page. These events can occur automatically or can be triggered by user actions.

Examples of events include click (pressing mouse button), change (e.g an input field changing), load (when an object has been loaded, often used with the body element) and so many more.

Events also possess properties that provide more information about that event. Find a list of those properties in the MDN docs.

Among these properties, I’d be explaining the target property, which can be accessed like this, event.target

target , is a property of an event which is a reference to the element upon which the event was fired. Just as ‘target’ means ‘aiming at something’, it’s used to ‘aim’ at that particular element.

This property gives us access to the properties of that element.

NOTE that this property is different from currentTarget . currentTarget returns a reference to the actual object that fired the event while target returns a reference to the object of which the event was fired upon regardless of the element that listened to the event.
Check out the pen below to understand the difference better.

See the Pen currentTargetVStarget by Dillion Megida

Since the target property has given us access to the element, we could then read some of the properties (which are the attributes) and also display them somewhere else.

The most common use case is in input elements. For example, a change event is listened to on an input field. This event is fired once there is a change in the content of that input (which could be a change in value). The value of the input could then be transformed or displayed somewhere else.

Check out this pen — A simple program that displays the value as it changes.

See the Pen event.target.value by Dillion Megida

Let’s analyze the code used.

  • The reason I added the event listener to the input instead of the container is that I do not want to listen to every change event on the container. Other change events could occur in it such as select tags or textarea . Hence, I listened to only change events in the input tag.
  • I set variable references to the input tag and the initially empty h1 tag.
  • I listened for every change event on the input and applied a function that sets the value of the input to the content of the h1 tag.
  • I used the target property to target the input.

You could also use the property to set attributes of an element. For example, the class attribute. Let’s say you have a class attribute of ‘red’ which changes the text color of elements to red, you could have this;

style> .red  color: red; > style> p id="toBeChanged">My color can changep> script> function changeColorToRed(event)  event.target.className = "red" > let toBeChanged = document.querySelector("toBeChanged") toBeChanged.addEventListener("click", changeColorToRed, false) script>

If you tried this code, you’d notice that when you click on the paragraph, its color changes to red.

There are other use cases that could be made out of this property. From the above examples which showed how to get properties and set properties of elements which events were fired on, I believe you’d be able to create more interactive applications.

The target property of events allows us to access the element of which the event was fired and its respective attributes. We can further get the properties or even set them.

Articles written with ❤ by
Dillion Megida

Источник

Understanding event.target and Use Cases

Blog Cover

Profile picture

The Event interface represents an event that takes place in the Document Object Model [DOM].

Events refer to happenings in the DOM from the loading of a page to the navigation to another page or the closing of a page. These events can occur automatically or can be triggered by user actions.

Examples of events include click (pressing mouse button), change (e.g an input field changing), load (when an object has been loaded, often used with the body element) and so many more.

Events also possess properties that provide more information about that event. Find a list of those properties in the MDN docs.

Among these properties, I’d be explaining the target property, which can be accessed like this, event.target

target , is a property of an event which is a reference to the element upon which the event was fired. Just as ‘target’ means ‘aiming at something’, it’s used to ‘aim’ at that particular element.

This property gives us access to the properties of that element.

NOTE that this property is different from currentTarget . currentTarget returns a reference to the actual object that fired the event while target returns a reference to the object of which the event was fired upon regardless of the element that listened to the event.
Check out the pen below to understand the difference better.

See the Pen currentTargetVStarget by Dillion Megida

Since the target property has given us access to the element, we could then read some of the properties (which are the attributes) and also display them somewhere else.

The most common use case is in input elements. For example, a change event is listened to on an input field. This event is fired once there is a change in the content of that input (which could be a change in value). The value of the input could then be transformed or displayed somewhere else.

Check out this pen — A simple program that displays the value as it changes.

See the Pen event.target.value by Dillion Megida

Let’s analyze the code used.

  • The reason I added the event listener to the input instead of the container is that I do not want to listen to every change event on the container. Other change events could occur in it such as select tags or textarea . Hence, I listened to only change events in the input tag.
  • I set variable references to the input tag and the initially empty h1 tag.
  • I listened for every change event on the input and applied a function that sets the value of the input to the content of the h1 tag.
  • I used the target property to target the input.

You could also use the property to set attributes of an element. For example, the class attribute. Let’s say you have a class attribute of ‘red’ which changes the text color of elements to red, you could have this;

style> .red  color: red; > style> p id="toBeChanged">My color can changep> script> function changeColorToRed(event)  event.target.className = "red" > let toBeChanged = document.querySelector("toBeChanged") toBeChanged.addEventListener("click", changeColorToRed, false) script>

If you tried this code, you’d notice that when you click on the paragraph, its color changes to red.

There are other use cases that could be made out of this property. From the above examples which showed how to get properties and set properties of elements which events were fired on, I believe you’d be able to create more interactive applications.

The target property of events allows us to access the element of which the event was fired and its respective attributes. We can further get the properties or even set them.

Articles written with ❤ by
Dillion Megida

Источник

Читайте также:  Python check if list contains value
Оцените статью