I am trying to understand events(such as: click, keyPress...) in js. But when I studied online, I saw it mentioned a lot on 'DOM events'. So my question is js events the same as DOM events? If not, what is the difference?
DOM events fires when the DOM changes or interacts with user, and they are Javascript events.
Please have a read all of them: http://www.w3schools.com/jsref/dom_obj_event.asp
Apart from DOM events, you can define your own event objects in Javascript and use the 'dispatchEvent' method to fire that event. For example:
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
elem.dispatchEvent(event);
In short, you can think of DOM events are native Javascript events that fires from DOM elements. While a Javascript event can be a DOM event or Custom event
A DOM event is any event that elements or objects in the DOM listen on. For example, a button click, a text input keypress, a mouseover. Generally DOM events are triggered by some sort of user interaction (mouse events, keyboard events, form submissions etc). DOM events can be triggered programatically though.
There are other events that wouldn't be regarded as DOM events, for example:
AJAX response (onreadystatechange)
WebSocket message received (MessageEvent)
LocalStorage data changed (storage)
An event is a system when certain actions performed are recorded and can be acted upon. Such as clicking on a button, hovering over some box, selecting some text, or even receiving a new message on a certain channel.
In js, DOM events are standard events that correspond to actions performed directly on an element in the DOM such as when the user clicks on something, the click event(directly corresponding to the user clicking the button) is triggered and any event handlers attached to the element will be called.
Here's a list of events:
https://en.wikipedia.org/wiki/DOM_events
These are recognized and supported by the browsers and are natively triggered.
Many js libraries make their own system of events over these DOM events. They wrap around the element that is listened to and when an event is triggered, they propogate the event to the handling function
They can also support custom events on DOM or any other object by having the user call a specific function such as
obj.on("receive", function(){alert("Hello")})
//Later
obj.trigger("receive")
So the anonymous function(display an alert) will be called whenever you trigger the receive event. What happens here is that the on function will keep a list of handlers attached to the object and the trigger function will call each one and call them using any required data
Dom Events: This event perform on the DOM component to perform certain action over it like (events/properties,etc)
Js Events: This events will perform action over the content of the DOM object like (validation(condition),expression,methods over the Dom object,etc)
Related
I know how trigger a function when an element loads in with jQuery but can't seem to figure it out in pure Javascript. I would like to do this is JS.
So I know how to fire a function in jQuery when an element loads but I want to do it in Javascript. I would like to do this is pure Javascript.
$('img').load(
function(){
//do stuff
})
From the MDN documentation of the load event:
The load event is fired when a resource and its dependent resources
have finished loading.
As mentioned in the comments, an input element has no dependent content to load, hence a load event for it will never trigger.
It's important to understand that all elements do need to be parsed into the Document's Object Model, but that is a process that must complete before you can programmatically interact with the element in the first place.
Once the client has finished parsing all the elements in the DOM, the client will fire off its "DOMContentLoaded" event (equivalent to the JQuery $(document).ready event shown in the W3 Schools example you linked to). It is at this point that it is safe to search through the DOM and locate elements to be worked with.
From there, different elements can/will have different events that can occur on them during their lifetime. An input element will respond to user input and interactions, so it has several different events to tie into them (input, change, keydown, keyup, keypress, mouseup, mousedown, focus, blur, etc.).
For a load event, you need to work with elements that contain content that needs to be loaded into them after the element itself has been created. Examples would be window, img, iframe, link. These are all elements that need external content for them to be of any use to anyone.
So, take an element like an img which needs to load an external resource and the pure JavaScript would use the native DOM API way to register event callbacks, which is with the element.addEventListener() method.:
// Get a reference to the DOM element.
// Make sure this is done AFTER the DOM has finished loading:
var img = document.getElementById("someImgageElementsID");
// Register a function to the image's load event handlers:
img.addEventListener("load", doLoad);
// Declare the callback function:
function doLoad(){
console.log("image loaded");
}
More on element events.
Dispatching an event means firing it. the following code will fire the click event of the button 2 times.
let event = new Event("click");
elem.dispatchEvent(event);
elem.dispatchEvent(event);
<button id="elem" onclick="alert('Click!');">Autoclick</button>
Javascript has classes that are listening to the user events (click, hover a button, press a key). That classes are the event dispatchers. What does "dispatch a event" means?
The event dispatchers manage the event in order to "understand" which action has made the user and react with the behaviour that the developer coded.
Javascript has some event dispatcher classes defined by default, but some libraries like JQuery let you create custom events.
To understand a custom event, you can think this example: You are programming a clock class that you will use in the future. You code all the methods to make the clock work. Further, you declare a new event that triggers when a second passes. Let's call it "timestep".
Now imagine you use that class in two different programs. You can implement a different behaviour in both programs by inserting code in the "timestep" event.
In this example, I created a custom event that fires when the user moves one handle. It's behaviour consist in modify the label to the time the handle is on. Check it here:
http://ytcropper.com/crop/hsceS7udV4g
Could someone explain to me what exactly this means
trigger executes the code for the event handler but not actually executes the event itself?
Consider the following code:
$('#parent').on('click',function (event){
console.log(event);
});
$('#parent').trigger('click');
trigger does produce an Event object since it consoles it. So, in which way it does not execute the event?
jQuery has a rather nice event system, that handles events in a more complex way than the basic event bubbling. For instance it allows multiple events, of the same type, on an element.
That means that jQuery events sit on top of the browser events and add features. When you trigger a jQuery event it just send messages up the jQuery DOM tree, which causes things to respond, but it does not necessarily generate the native browser events.
You can still hit the native event generation by using the underlying DOM elements and methods that jQuery wraps:
// This will generate a click event "for jQuery to hear"
$('#parent').trigger('click');
or this does exactly the same as above:
$('#parent').click();
Whereas this will fire the native DOM click event "actually clicks the button/link":
$('#parent')[0].click();
Update (from A. Wolff):
Some jQuery click events are passed on to the native click event. An exception being anchor links (which do not). I would have to test it to see if native clicks are generated or not for buttons and other inputs.
is there any universal way to instrument javascript event handler firing using javascript?
for example, I want to do something before the event handler firing, so when to fire an event, I would like to execute my code first then the event handler code.
The problem is that there are multiple ways to register event handlers, I would like to handle all of them: html, javascript
No, there's not.
You can hook addEventListener and removeEventListener, which would allow you to intercept both the registration and invocation of event listeners by JS code. However, this will not capture event listeners set in ways such as elt.onclick. Nor of course will it catch listeners set up via the old IE attachEvent API. Most importantly, it will not help with you that events that are generated and listened for internally, such as a mouse click on a check box.
You might be tempted to hook createEvent and dispatchEvent in similar fashion, but that will capture only events that are explicitly created or dispatched in the JS code.
I have a page, on the left there is a list of links users can click, when they are clicked, a div on the right side will load the correct content via Ajax according to the link.
Now I want to fire a function when the right side div's content changed every time.
After a search in Stack Overflow, I learn that there are Mutation Events, I use the DOMSubtreeModified event:
right_div.addEventListener("DOMSubtreeModified", handler, false);
However, when I click the link on the left side, it seems that handler will be called several time. I want it be called only once when the new contents of it has been loaded. How could I do this?
The DOMSubtreeModified is "a general event for notification of all changes to the document". You can set mutation events for specific mutations:
DOMAttrModified event
DOMCharacterDataModified event
DOMNodeInserted event
DOMNodeInsertedIntoDocument event
DOMNodeRemoved event
DOMNodeRemovedFromDocument event
And there are the following types:
DOMElementNameChanged
DOMAttributeNameChanged
So if you are replacing a node, it might cause two (or more) mutation events - one when the node is removed, another when it is replaced. Futher events may also be dispatched, such as character data modified. if you are listening for an event only when the text content is changed, try the DOMCharacterDataModified event:
A user agent must dispatch this event
after CharacterData.data or
ProcessingInstruction.data have been
modified, but the node itself has not
been inserted or deleted. The proximal
event target of this event must be the
CharacterData node or the
ProcessingInstruction node.