Stopping events to bubble up in DOM - javascript

I am writing a HTML editor, anyone can plug this plugin into their site and make use of it.
Plugin Usage
$(".editable").htmleditor();
Onclick on this elements I will change the element into contenteditable and my editor menu will be opened near the element like aloha editor.
Problem
Scenario 1
<div class='editable' onclick='loadUrl('https://facebook.com')'>
</div>
Scenario 2
<div class='editable' id='openNewWindow'></div>
<script>
$("#openNewWindow").click(function(e){
e.preventDefault();
e.stopPropagation();
});
</script>
Aforementioned scenarios I won't receive the event. It makes my plugin not reliable. I tried couple of solutions.
Solutions I tried
Removed all elements in a body and reinserted into it again to remove attached event handlers. It works but the UI is distorted while inserting in some sites.
Added onclick='return false' attribute in all elements. It works for some elements only.
How to unbind all attached event handlers and prevent the default event of an element?

In Scenario 1, the user of your plugin has both made an element editable, and also made clicking on it navigate away from the current page. That doesn't make much sense, but it's their business. In this situation they can't realistically expect your plugin to run.
In Scenario 2, you need to process the click event before it's handled elsewhere. Removing or suppressing existing handlers is not a good idea: it may make other parts of the page fail, and is annoying to your users in any case.
Instead, you can make your handler run in the event capture phase like this:
editableElement.addEventLister("click", myHandler, true); // note the "true"
Now your handler will run before all handlers added using JQuery (and most handlers that people add via any means), which run in the event bubble phase. Note that this technique only works in modern browsers (i.e., not IE < 9).
For reference: What is event bubbling and capturing?

Related

Click event for each element or one click event on the document for all?

Let's say I have bunch of click events. Also one/few of them is for document object.
Which one is better for performance? Click event for each element or :
document.addEventListener('click', (e)=>{
if(e.target == firstObject){ firstFunction(e) }
if(e.target == secondObject){ secondFunction(e) }
if(e.target == ThirdObject){ thirdFunction(e) }
})
Neither is "better." They each have their place in your toolkit.
A single delegated handler is more complex in that you have to do the kind of dispatch you're doing in your example (often using closest or matches), but has the advantage that if you're adding/removing elements you want to act on, you don't have to juggle event handlers.
Directly-assigned handlers are simpler (at least on elements that aren't added/removed), can prevent propagation, and let you keep your code more modular, more in keeping with the single responsibility principle.
Use the one that makes the most sense in a given context.
I think event listener for each element is better if possible, and makes sense in terms of code quality. There are some cases though where a document event listener will be needed ( for example to emulate a click outside behaviour)
That being said here are some of reasons that makes event listener for each element a better solution
event propagation is handled for you by the browser, if you decide to have only one event handler for the whole document, and u want to have event listeners for elements that are contained in each other, then you will need to handle propagation your self. That is to say you need to handle the order in which functions run yourself, and then you will have some either complex generic solution, or a specific imperative verbose code with a lot of if else statements.
Easier to read code, this is even more true for recent frameworks for web like react, angular, etc..., so for example assume you want to have a listener for clicks on the document, where that code should reside, in which file, and which component should own the code.
Removal of event listeners is handled for you by the browser apis, the browser gives you a way to remove event listeners. If you decide to go with a global event listener then you should handle removing event listeners yourself.
Your code will be hard to refactor and easier to break later, because you are coupling your document (or container ) event listener to your components internals. That is if you decide to change the structure of these components later, your document based event listener will probably break. This will depend a lot on how you identify the target of clicks, for example if you were identifying them by class names or other attributes, then these attributes might change later for reasons like styling.
and if you depend on ids for example you might eventually have unexpected results. because what happens for example if you added a listener for an element that has id, removed that element, and then later added another element with same id.
You miss on the development tooling provided for you by browsers, browsers can show you attached listeners for elements, with a document based event listener you wont be able to do that
It's better if you add one by one, because then you can remove event whenever it finish. Moreover you have more control about this event.

SAPUI5: How to bind a click event to horizontal layout?

Hi I'm developing my view in JS and I'm stuck in binding a click handler for my horizontal layout element. I've tried using Jquery
$("#myHorizontalLayout").bind("click",function(){window.alert()});
Which didn't work then I tried using attachPress with the element which obviously didn't exist. Please help.
Update:
The JS view is the default view of the application.
When on/bind does not work, it could be that the HTML of the control has actually not been created yet at this point in time. But even if you delay the binding, the re-rendering (re-creation of the HTML after changes) would remove your listener, at least when bound on the control itself.
A proper way of doing this is using the generic attachBrowserEvent function available on every control (here: on the layout) which internally handles all the rendering/rerendering stuff, see this example:
http://jsbin.com/hijutunefi/1/edit?html,output
attachBrowserEvent works for any browser event, as it attaches a new browser event listener to the root node of the control. For the most common browser events UI5 does event delegation, so for the "click" event and several others addEventDelegate can also be used, as pointed out by aborjinik.
Alternatively, listening on the <body> level with normal jQuery mechanisms should in general also work.
Which didn't work then I tried using attachPress with the element which obviously didn't exist. Please help.
Does this means that the element on which you are attaching event handler doesn't exists at this point? If this is the case you can hook the handler to some container, upper in the DOM hierarchy which you are sure that exists and filter the click events.
Example:
$("body").on("click", "#myHorizontalLayout", function(){
alert("Hey, you!");
});
As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document. For earlier versions, the
.bind() method is used for attaching an event handler directly to
elements. Handlers are attached to the currently selected elements in
the jQuery object, so those elements must exist at the point the call
to .bind() occurs.
Reference here
So try replacing bind with on and let me know if it works or not.

Detect if CKEditor used a keyup event, or prevent its propagation

In short
Is there a way in which, when listening to a native event, I can detect if the event was somehow used by CKEditor before it propagated to my listener, or prevent it from propagating at all?
Use case
I'm listening to the keyup event using jQuery, to detect when escape is pressed. When it is, the user is prompted if they want to discard changes, and the CKEditor instance is destroyed and its element removed from the DOM.
$('body').on('keyup', function(e){
if(e.which==27){
CKEDITOR.instances.myDiv.destroy();
$('#myDiv').remove();
}
});
The problem here is that CKEditor allows the user to interact with certain UI elements using the escape key. For instance to close a dialog window or drop-down list.
So my event should only execute its code if CKEditor did not already use the event to close a UI element of its own.
Attempt
I tried to listen to the dialogShow and dialogHide events to detect if a dialog window is open, and my action should thus be ignored. This didn't work for two reasons:
CKEditor handles the event first, so by the time the event propagates to my listener, no dialog windows are open and my code is executed.
Even if it would work, it wouldn't for drop-down lists as they do not trigger the dialog* events.
Ideas
I don't know enough about the workings of CKEditor to come up with a solution, but I think I'm looking for something along the lines of:
A setting in CKEditor to prevent event propagation: CKEDITOR.instances[0].noEventPropagation = true
An indication in the original event object: if(event.CKEditorWasHere){/*do nothing*/}
A plugin providing functionality that I can use.
Worst case scenario: A setTimeout in the dialogHide event which I'll use to suppress my own events for a short time.
So
Maybe I'm completely overlooking something. This seems to me like a common problem which should have a simple solution.
Thanks for your time.

Twitter Timeline DOM Manipulation - Negating Onclick Event Handler

I am creating a browser extension that modifies the Twitter timeline by adding some links to each tweet row in a user's Twitter timeline.
Generally whenever the tweet row is clicked, Twitter will pop out the right-hand panel with more information, except for when the user clicks links like Retweet, Reply, etc. I'm not sure what Twitter's JavaScript is applying to these links to prevent them from causing the panel to be opened, but I'd like to do something similar. I have tried inspecting the elements in Google Chrome, but the event handlers are not revealed.
Any suggestions?
The event handlers are probably being added programmatically via script. You could try to remove the event handlers (see the docs), but it might be easier to clone the element in question, then hide the original. See cloneNode documentation for information.
Without any sample html, I can't really give you a good example, but here's a generic jsFiddle I threw together to demonstrate the concept: http://jsfiddle.net/sacCK/1/
I solved my problem by stopping the event propagation. This prevented the event from propagating to the event handler for the container element.
With jQuery I was able to apply an onclick handler like so:
$("#elementId").click(function(event) {
event.preventDefault();
event.stopPropagation();
// other actions
});

How do i turn this jQuery to javascript?

I have a facebook connect button on this site here is the code
<fb:login-button onlogin="javascript:jfbc.login.login_button_click();"
perms="email,publish_stream,user_about_me,user_hometown,user_location,user_birthday,user_religion_politics,user_interests,user_activities,user_website"
size="medium" v="2"><a class="fb_button fb_button_medium">
<span class="fb_button_text"\>Login With Facebook</span></a></fb:login-button>
and i want to trigger this button with a javascript call and doing research i found this jquery that seems that it would do the trick (havent tested though) and i was wondering if there is an equivelent javascript or mootool because jquery is not installed. I can install it if i cant find a solution. Or if anyone has another idea on how to trigger this facebook button
$("fb\:login-button").trigger("click");
There are two ways to "trigger" a listener:
call it directly (e.g. element.onclick())
dispatch an event into the DOM that the listener will respond to
The trouble with the first method is that it doesn't replicate a bubbling event so the listener may not work as intended (e.g. there is no associated event object or bubbling, the listener's this keyword may not be correctly set).
The trouble with the second is that some browsers will not allow programatically dispatched events to do certain things (click on links for example). Also, in some browsers you have to use the W3C dispatchEvent and in others the Microsoft fireEvent.
So unless the listener has been designed specifically to work with one method or the other and is called appropriately, your chances of triggering the listener successfully are quite low.
PS. Some libraries provide their own event system, with custom events and bubbling of otherwise non-bubbling events, but in that case you have to set and trigger the listener using that library, otherwise it will probably not respond to either of the above methods.
You should be able to just invoke the same code that is invoked inline:
jfbc.login.login_button_click();
I suppose it would be something like
document.getElementsByTagName("fb\:login-button")[0].click();
I'm sure that would work very well with a "normal" DOM element that handles the click event; however, I'm not entirely sure it will work in all browsers with the fb:login-button element shimmed into HTML. You'll have to let me know.
Looks like you should be able to do:
document.body.getElementsByTagName("fb\:login-button")[0].click();
It looks like you want a namespaced element selector, so you should use:
document.getElementsByTagNameNS('fb', 'login-button')[0].click();
The : is the namespace separator.
I ran into this tonight, absolutely positioned a new button image over the iframe, and was planning on using pointer-events:none to pass through and click the iframe, but I was looking for a cross-browser solution, here you go.
jQuery('.button_fb_connect').live('click', function(){ FB.login() })
Your simply running the js function FB.login() after clicking your new element, obviously you can use whatever event you want.
Thats in jQuery of course, but thats the function you want, not just a simple click event trigger.

Categories

Resources