<script>
console.log("Hello World!");
</script>
<script src="js_file.js"></script>
objectName.propertyName
document.getElementById('id_of_element')
=> returns a single elementdocument.getElementsByClassName('class_of_element')
=> returns array like structure containing matching elements.document.getElementsByTagName('tag_of_element')
=> returns array like structure containing matching elements.document.querySelector("#id-name")
, querySelector(".class-name")
, querySelector("ul")
=> returns single matching element.document.querySelectorAll('#id-name')
=> returns array like structure containing matching elements.document.createElement('p')
;element.appendChild('li')
;element.removeChild('li')
;When you browse the web, your browser registers different types of events. It’s the browser’s way of saying, “Hey, this just happened.” Your script can then respond to these events.
Scripts often respond to these events by updating the content of the web page (via the Document Object Model) which makes the page feel more interactive.
EVENTS FIRE OR ARE RAISED
EVENTS TRIGGER SCRIPTS
When the user interacts with the HTML on a web page, there are three steps involved in getting it to trigger some JavaScript code. Together these steps are known as event handling.
Steps:
Three Ways to bind an event to an element:
HTML Event Handlers
<input type="button" onclick="alert('Click!')" value="Button">
<input type="button" id="button" value="Button">
<script>
button.onclick = function() {
alert('Click!');
};
</script>
Note: As there’s only one onclick
property, we can’t assign more than one event handler.
Event Listeners
Event listeners are a more recent approach to handling events. They can deal with more than one function at a time but they are not supported in older browsers.
Unlike, other two method in this method we can add multiple event listeners and they will execute in the order they are define
The Event Object
When an event occurs, the event object tells you information about the event, and the element it happened upon.
To properly handle an event we’d want to know more about what’s happened. Not just a “click” or a “keydown”, but what were the pointer coordinates? Which key was pressed? And so on.
When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.
Here’s an example of getting pointer coordinates from the event object:
<input type="button" value="Click me" id="elem">
<script>
elem.onclick = function(event) {
// show event type, element and coordinates of the click
alert(event.type + " at " + event.currentTarget);
alert("Coordinates: " + event.clientX + ":" + event.clientY);
};
</script>
Some properties of event
object:
type
currentTarget
target
preventDefault
stopPropagation
Note: What is the difference between currentTarget
and target
?
Event Flow
<body>
<ul>
<li><a>Link</a></li>
</ul>
</body>
Bubbling - The bubbling principle is simple.
Event Delegation