in Javascript: Is there a way of checking if a mouseover event for some element has fired?
If yes, how?
T
var mousedOver = [];
function addToMousedOverElements(obj) {
mousedOver[mousedOver.length] = obj;
}
You could create a callback to add the moused over element to a list.
mouseover me!
Or, something similar. This would then allow you to reference each element that has been moused over. You may also want to check to see if the element has been moused over yet before adding it to the list.
Lets suppose you want to track mouseover event on a bunch of elements. Since, mouseover event gets bubbled up in JS, attach a onmouseover handler to a node that is a parent node to these elements.
Consider the following html:
`<div id="parent">
<div id='div1'>Track mouseover on me</div>
<div id='div2'> Track mouse over on me too.</div>
</div>
So for such an HTML, you can attach the handler to the div called 'parent' like
document.getElementById('parent').onmouseover = function(e){
e = e|| window.event;
if(e.target.id=='div1')
//handle mouseover for first div;
};
`
and so on. Like this, you can have a generic function handler for a bunch of elements.
Dealing with raw Javascript can be troublesome, particularly cross-browser. You are best off using a library like jQuery to handle this:
jQuery onMouseOver
Although such libraries do tend to increase the size of your webpages you can still get good performance by using a CDN such as:
Google's AJAX CDN
Microsoft's AJAX CDN
for example for a div:
<div onmousemove="alert('doSomething')">waiting for mouse over...</div>
you can replace alert by any javascript function.
more informations here: Javascript - Mouse Events.
This does the job:
<head>
<script language="JavaScript">
function myFunction(){
alert('Mouse over!!!')
}
</script>
</head>
<body>
<div id="myDiv" onmouseover="myFunction()">
Mouse over here...
</div>
</body>
Related
I have following html on my page:
<div class="group-one" >
<p><span id="handle" draggable="true">::</span> click me</p>
</div>
<div class="group-two" draggable="true">
<p>I should be dragged</p>
</div>
Now what I want is that when #handle is dragged, the drag event should be delegated to div.group-two and element under move cursor should be div.group-two either. This is what I have tried:
$('#handle').mousedown(function(e){
$('.group-two').trigger(e);
});
$('#handle').on('dragstart', function(e){
$('.group-two').trigger(e);
});
$('.group-two').on('dragstart', function(e){
console.log('dragestart triggered on group-two');
});
$('.group-two').mousedown(function(e){
console.log("mousedown triggered on group-two");
});
Here is a jsfiddle.
The problem here is that although event is delegated to div.group-two but element being dragged under the move cursor is still span#handle.
Now my question is that, Is it possible to delegate drag in this manner? If it is, then any hint how to achieve it.
Note that I am using plain jQuery not jQuery UI.
Probably not. Personally it doesn't work for me, and after a bit of digging I found this extension someone made to help resolve it: https://www.bitovi.com/blog/delegate-able-drag-drop-events-for-jquery
I suspect it has something to do with the originalEvent being a trusted event and hence we can't modify its contents.
If you don't want to use the extension, perhaps consider relying on the quirk that users can only drag one thing at a time; and hence storing the data in a global variable (if its just going to be in the browser) would work. That's what I'm about to do :)
I have a simple mouseover event that I am trying to work on elements that are loaded with ajax. For example I have a div that when you mouseover hide/show another div. When I load these divs through ajax they no longer work. For example :
<div class="block">
<div class="something">MOUSEOVER</div>
<div class="else" style="display: none" >HI</div>
</div>
$(document).ready(function(){
//using on hoping to catch the mouse events
$('.block').on('mouseenter',function(){
$(this).children('.else').fadeIn('fast');
});
$('.block').on('mouseleave',function(){
$(this).children('.else').fadeOut('fast');
});
});
This works fine straight up like this :
But when I load those elements from another page :
$j('#trigger').load( url + " .block");
The mouse events are no longer recognized. I thought this is what live, on, delegate were for. Can someone help me figure this out please.
One possibility is to change your code like:
var myFunc = function() {
$('.block').on('mouseenter',function(){
$(this).children('.else').fadeIn('fast');
});
$('.block').on('mouseleave',function(){
$(this).children('.else').fadeOut('fast');
});
}
$('#trigger').load(url + " .block", function() {
myFunc();
});
to make this functions like mouseenter or mouseleave in the loaded content possible.
The other possibility is $.live();. Like:
$('.block').live('mouseenter', function() {
//here your code
});
This is exactly what methods like on and delegate can be used for, but they have to be used correctly.
As events bubble from the element on which they originated up through the DOM you need to capture the event on an ancestor element that already existed:
$(".someAncestor").on("mouseenter", ".something", function() {
//Executed when .something triggers the mouseenter event
});
It looks like you are loading the entire .block element via AJAX, so you will need to bind the event somewhere higher up the DOM tree (probably the element inside which you append .block).
You can put the trigger event to load on AJAX success.
I'm working on a web framework and am trying to build XSS prevention into it. I have set it up so it will escape incoming data for storage in the database, but sometimes you want to save html that the user generates. I am trying to make a custom tag that will prevent any javascript from executing, here is my first hack at it:
<html>
<head>
<script type="text/javascript" src="/js/jquery.min.js"></script>
</head>
<body>
<preventjs>
<div id="user-content-area">
<!-- evil user content -->
<p onclick="alert('evil stuff');">I'm not evil, promise.</p>
<p onmouseover="alert('evil stuff');">Neither am I.</p>
<!-- end user content -->
</div>
</preventjs>
<script type="text/javascript">
// <preventjs> tags are supposed to prevent any javascript events
// but this does not unbined DOM events
$("preventjs").find("*").unbind();
</script>
</body>
</html>
I tried using jQuery to unbind everything, but it doesn't unbind events in the DOM, which is exactly what I'm trying to do. Is it possible to unbind all events for a DOM element?
You're problem is that you are doing this on the wrong end of things -- you should be filtering all user input of potentially hostile content when you receive it.
The first rule of thumb when doing this is "always whitelist, never blacklist". Rather than allowing any and all attributes in your user-generated HTML, simply keep a list of allowed attributes and strip away all others when you receive the HTML (possibly on the client side -- definitely on the server side.)
Oh, and HTML is not a regular language. You'll want to use an HTML parser, not a regular expression for this task.
.unbind will only unbind events attached using jQuery. You can get rid of inline event handler code by setting them to null, e.g.:
$("preventjs *").removeAttr("onclick").removeAttr("onmouseover");
Demo.
EDIT: Here's an evil solution, you can remove all attributes starting with "on":
$("preventjs *").each(function() {
var attribs = this.attributes;
var that = this;
$.each(attribs, function(i, attrib) {
if(attrib.name.indexOf("on") === 0) {
$(that).removeAttr(attrib.name);
}
});
});
Demo.
The problem is that you've inline handlers. unbind cannot remove inline handlers.
<p onclick="alert('evil stuff'...
^^^^
To remove inline handlers, use removeAttr
$("preventjs").find("*").removeAttr('onclick');
$("preventjs").find("*").removeAttr('onmouseover');
You can unbind the events individually:
$('p').each(function(){ this.onclick = this.onmouseover = undefined; });
If you want to unbind other events like mouseout you have to add them to that list:
$('p').each(function(){ this.onclick =
this.onmouseover =
this.onmouseout = undefined; });
Of course you'll want to use a selector other than $('p'), I just didn't want to put your other one because preventjs is not an HTML tag
Is it possible to get anywhere a pure Javascript function for event handler with similar functionality as jQuery's live() ? I need to have the ability to attach events to objects not yet created but both jquery-livequery as well as jquery-events sources are not useful due to dependencies on jQuery core.
Event delegation is quite simple. Take this example:
Markup:
<div id="container">
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
<button id="add">Add new paragraph</button>
Script:
document.getElementById("container").onclick = function(e) {
// e.target is the target of the event or "source element"
alert(e.target.innerHTML);
};
// dynamically adds new paragraph on button click
document.getElementById("add").onclick = function() {
var p = document.createElement("p");
p.innerHTML = "a new paragraph";
document.getElementById("container").appendChild(p);
};
Since the event handler is attached to the parent, it will work for any future elements inserted.
You can try it here.
Useful reference:
http://www.quirksmode.org/js/events_properties.html#target
http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
Yes, it's called event delegation and has been around longer than jQuery and "live".
"live" works by listening for events on the body or document, then when when an event occurs looks at the event.target to see if it's selector matches one of those stored in a cache. It is quite inefficient, but works OK for some.
A more efficient approach is to add elements you want listeners on to an array, then listen for bubbling events on the lowest common ancestor of the elements you want to delegate events for. The body element is the fallback, but it's the least efficient. When the listener gets an event it's waiting for, check if the event.target is one of the elements in the array and if so, call the related function with the element as this.
You can also just store the element id as a property of an object so looking it up is faster if you have lots of elements, or you can register events based on class.
There are a few limitations and foibles (some events bubble in some browsers but not others, and some don't bubble at all), and it can be very inefficient, so use with care.
I know little of Jquery and your functions.
You are looking how works with events in javascript?
You can make this:
element.addEventListener('onclick',
function() {
//do something
});
or
element.onclick =
function() {
//do something
});
the element var is an reference of dom document.
check https://developer.mozilla.org/en/DOM for more details.
JQuery is pure JavaScript and OpenSource, so just have a look into the sources, then copy what you need and adapt it.
Im trying to remove a class once the user hovers over a link.
Here is the HTML:
Fonctionalites
<div id="commercial_dd_total_FONCTIONALITES" class="menu_hidden">
<a class="commercial_dd_bg">Item One</a>
</div>
JS:
<script type="javascript">
$(document).ready(function(){
$("#menu_fonctionalites").hover(
function () {
$("#commercial_dd_total_FONCTIONALITES").removeClass("menu_hidden");
}
);
});
</script>
This isn't working.... any ideas about what I've done wrong?
http://jsfiddle.net/tuFru/1 it appears to be working here. You might include the CSS and describe what exactly isn't working for you. I updated it to take advantage of the second argument for hover as defined below:
Description
Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
version added: 1.0.
hover( handlerIn(eventObject), handlerOut(eventObject) )
handlerIn(eventObject)A function to execute when the mouse pointer enters the element.
handlerOut(eventObject)A function to execute when the mouse pointer leaves the element.
The .hover() method binds handlers for both mouseenter and mouseleave events. We can use it to simply apply behavior to an element during the time the mouse is within the element.
Calling $(selector).hover(handlerIn, handlerOut) is shorthand for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
See the discussions for .mouseenter() and .mouseleave() for more details.
If you are just trying to toggle visibility you could probably just add the normal class for the div styling and toggle it using the jQuery hide()/show() methods.