jquery detect change in dom outsite jquery - javascript

Is it possible using jQuery (or any other JavaScript function) to detect when an onmouseover event is fired?
I have a page where existing javaScript calls a onmouseover/out events to re-write the contents of the div. I'm actually only interested in getting at what the div contains while the mouse is hovered over it. The onmouseover event is generated server-side by a program I don't have the ability to change :(.
Any suggestions on how to accomplish this?

$("#idOfYourControl").hover(function() { /*mouseover event*/ }, function() { /*mouseout event*/ });

Here's an even more specific example:
$("#idOfYourControl").hover(
function() { $('#divToShowText').text($(this).text()) },
function() { $('#divToShowText').text("") }
);

You can use the mouseover event handler in jQuery.
http://docs.jquery.com/Events/mouseover#fn

Depending on how the server is writing the original mouseover handler out, you can use a simple overwrite to add your own hook that you can then use to detect the old one being fired:
var oldHandler = yourElement.onmouseover;
yourElement.onmouseover = function() {
//Do whatever new code you want here...
$j.trigger('oldHandlerCalled');
oldhandler();
}
Kind of a quick and dirty example, but you get the idea. No guarantees that this won't leak memory in IE6 ;)
If the server is attaching the event via jQuery, you can look in yourElement.data.events and do it in a much tidier way than this.

Related

Adding code via addEventListener without loop by mouseover

I want to add some code by addEventListener. I would use DOMContentLoaded, but ID which I'm trying to select is not available on page load. I could use mouseover, but it iterate the code on any move. I could also use click event, but I don't want it show on click, but just when it's shown. How can I handle it?
document.addEventListener("mouseover", function(event){
document.querySelector("#id").insertAdjacentHTML('afterend', '<div>asd</div>');
});
You need to delegate
var yourSpecificId = "some-id";
document.addEventListener("mouseover", function(event){
if (event.target.id == yourSpecificId ) //only when the id of the mouseover element is matching yourSpecificId
{
//code you want to execute
}
});
I would suggest a Mutation Observer. It looks hard to implement, but it's very easy. You can provide a callback function, and then a quick if statement to check if the newly added element has the correct id. If so, run your code and disconnect the observer.
It would be easier to help you if you posted a working example of when an element is added and the function you need to run.
Read this blog: https://davidwalsh.name/mutationobserver-api

Best way to slim down my code on onclicks

I am not great at javascript/jquery for the most part but I know how to get some software to work. But my issue is that I have a whole bunch of
$("body").on("click", "button#thisid", function(event) {
//do stuff here
});
There are alot of the on clicks that use jquery post and get functions but they all have tiny and simple differences that i need to have get sent through. I dont want every single button to have an onclick event but I am not sure how to bind the event to a large list of items that need to have it attached to.
I have been trying to come up with some way to slim all these down but I want to have the best approach instead a whole bunch of crash and fails. So I am reaching out to people who know more than me in order to lead me in the correct path.
Please help
Considering your elements are dynamically injected, you will need to apply the click handler to an element that always exist on page load:
$(document).ready(function() {
$(document).on("click", "button.target", function() {
console.log($(this)[0].id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="target">One</button>
<button id="2" class="target">Two</button>
In the above example, the click handler is applied to document, and triggers whenever a button element with the class of target is clicked, running the code inside the function.
To combine the .get() and .post() functions, you'll have to find synonymous data. Keep in mind that you have access to $(this), so you can extract the relevant ID if need be :)
Hope this helps!
I dont exactly get what you want to do...
But the $("body") is the jquery selector which defines on which elements your listener will be bound to.
So if you want to create a listener for more different elements the probably easiest solution is creating a class like "listenedElement" which you give to every element you want the listener to react to and write write the selector like this
$('.listenedElement').on( "click", function() {});
If you just look for click listeners this one looks pretty nice as well:
https://api.jquery.com/click/
A nice way I find is having a one line for each button like so:
$('#model').on('click', openModel());
$('#openDropdown').on('click', openDropdown());
$('#shoppingCart').on('click', shoppingCart());
And then defining each of these functions:
function openModel() {
// Stuff here
}
function openDropdown() {
// Stuff here
}
function shoppingCart() {
// Stuff here
}
So instead of writing the function as a parameter, I find it neater to just do it separately and call it like above.

Can we name an event handler in Javascript?

I was messing around with jQuery and event handlers, when I noticed this:
That uses jQuery, and without it:
How does the popup get a bar saying jQuery? Do browsers have integrated jQuery support to detect that? Or is there some way to name event handlers? I want to have my event display some other text, like how jQuery does.
NOTE: I don't want to use jQuery, as I want to know how jQuery does it.
I am not sure about what you are trying to do, but in Javascript you can always name functions
Example:
function myEventHandler(event) {
alert('event handler');
}
myEventHandler is the name of the function.
Hope this helps a little,
best,
Carsten
You can have custom names for your events if you want. We can use the trigger function for the same purpose.
Suppose you want to raise myEvent on <div id="my_div">.
We can simply
$("#my_div").trigger('myEvent');
and have a listener for the event:
$("#my_div").on('myEvent', function(event){
//Event handler
});
You can find some good documentation here -
https://learn.jquery.com/events/introduction-to-custom-events/
And this SO answer covers it thoroughly -
Custom events in jQuery?

Is .unbind().click(function() {...}) a good practice?

I'm talking about the following:
.unbind().click(function () {
// Do something
}
It looks a bit dodgy to me, however it makes sense: the developer wants to first remove any events bound to the element and then bind a click event.
Is there a better solution for this issue? Or correct my way of thinking.
It's not really good practice, because you do not control which click events get unbound. There are two different approaches to improve this:
Use event namespaces (faster)
You can use a namespace to control you unbind just the click event you're going to bind again:
$(selector).off('click.namespace').on('click.namespace', function(e) { //...
Use classes (fastest)
Use classes added to the link to mark it as registered (this does not unbind previously bound events, but it helps preventing multiple event bindings, which is the issue in most cases you would use off (unbind) before on (bind):
$(selector).not('.registered').addClass('registered').on('click', function(e) { //...
You can even turn this into a little sexy plugin, writing:
$.fn.register = function(register_class) {
register_class || (register_class = 'registered'); // lets you control the class
return this.not('.' + register_class).addClass(register_class);
};
Like this, you can just call register on every selector:
$(selector).register().on('click', function(e) { //...
Or with a specific class, if «registered» is taken:
$(selector).register('special_handler_registered').on('click', function(e) { //...
Performance?
If you wonder about the performance of the different handlers:
Check out this performance test here
I followed this approach whenever I had to "renew" some button, link, ect., behavior, and I think there's nothing wrong with it.
But be aware that with your code you'd be removing every handler attached to the element(s). So, instead:
$(selector).unbind('click').click(function(){
// do something
})
Well, at least it is good practice to specify which event handlers should be unbinded. So if there was some click event hendler and we want to unbind only it, then we can use unbind('click').
As there can be some other handlers in addition to yours, it make sense to use namespaces.
$(selector).off('click.myns').on('click.myns', function() {....})
or
$(selector).unbind('click.myns').bind('click.myns',function() {...})
This way you will only touch your own handler and not some others, for instance added by jquery plugins
I usually try to used named event functions where ever possible in order to be able to unbind them explicitly:
$('a').unbind('click.myfunc').bind('click.myfunc', function(evt) { ... });
This way you could add this binding to an init-function that could be executed multiple times (handy for situations where you can't use delegate for whatever reason).
In general I would't try to unbind every event or even every handler of a certain event if I don't need to.
I'm also trying to stay current and replace all the bind/unbind calls with on/off ;-)

Is there any way to use javascript (jquery) to make an element behave **exactly** as if it was clicked (a unique situation)

I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.

Categories

Resources