How to call mouse over function on dyanamic divs - javascript

I have dynamic divs as rows:
<table border=1><tr><td>
<div id='div1'>fgg</div>
<div id='div2'>dfgdfg</div>
<div id='div3'>vcbcvb</div>
<div id='div4'>sdfsdf</div>
</td></tr></table>
How can I call jQuery function on mouseover of each div?
These divs are dynamic, can vary the number.

$("td div").live("mouseover", function() {
//mouseover code here
});
I suggest using a class for your divs, and using a selector: $(".rows") or similar. However, the above will work for the markup you've given.
If you must use id, this will allow you to add it by id. Keep in mind that as you add new items, you will have to run this code for the id (defeating the dynamic part of your original question).
$("#mydivid").mouseover(function() {
//mouseover code here
});
which you could utilize in a list like so:
var divs = ["mydiv1", "mydiv2", "mydiv3"];
$(divs).each(function() {
$("#" + this).mouseover(function() {
//mouseover code here
});
});
This is really a bad approach, I strongly suggest using a class instead.

Use event delegation, either .live() or .delegate() to bind events to elements that are created dynamically.

one another easy way is to give the same class name to all the divs.
you can hook the click event by class name instead of id.In the code you can also refer the current div block by using "this" keyword

Unless there is some reason you specifically cannot use a repeating class name for each div, the live() method is the way to go. Using a class would be much more efficient, however.

Related

Using (this) to select a specific instance of a class while hovering a parent element

I'm attempting to use jQuery to update the css of a specific instance of the child "slide-atc" class when the user hovers over its parent element of the "slide-block" class.
My only restriction is that I cannot edit the HTML directly. Here is some code that I was trying but I dont think im using .this() correctly
$(".slide-block").hover(function(){
$(this).(".slide-atc").css("bottom", "0px");
}, function(){
$(this).(".slide-atc").css("bottom", "-70px");
});
<div class="slide-block">
<div class="slide-atc">
</div>
</div>
Any help is greatly appreciated!
Your code has a syntax error: you will need to chain .find() in order to select the nested child, i.e.:
$(this).find(".slide-atc").css("bottom", "0px");
Alternatively, you can provide this as a second argument in a jQuery selector:
$(".slide-atc", this).css("bottom", "0px");
Please try using "this" without the $ sign.
The word "this" is a reference to the html element in the DOM itself that is the event source. In the other hand "$(this)" is a jQuery wrapper around that element that enables using other jQuery methods.
Also, I think you have an error at line 4 at as the second parameter is not a background-color.

Hiding the <p> and showing the <textarea> on a <a> click

I know the title sounds quite easy but the real problem is the markup. I have a link in a div which also in another div but the textarea and the paragraph are in another div so that's why I am having problem on how to show and hide elements in a completely different markuped div from a completely different markuped div.
I saw .parent() and .children() and .siblings(). But they couldn't help me or I think that I was not able to take help of those.
Here's the fiddle.
Here is the JS I tried:
$(".no_link").click(function(e) {
e.preventDefault();
});
$(".edit_offer").on('click', function() {
$(this).parent().parent().siblings().children("textarea").toggle();
});
You can use these selectors, but it will rely on the class username being in the heirarchy as you have in your code:
$(".edit_offer").on('click', function () {
$(this).closest('.username').find("textarea").toggle();
});
jsFiddle example
.closest() will traverse up the DOM until it hits the element with class username, then .find() will go down through the children looking for the textarea.
I did it using find(). http://jsfiddle.net/SZUT8/2/ To make the script more accurate and future-proof you could consider adding a class to the paragraph and matching it, as in here: http://jsfiddle.net/SZUT8/4/
You could always assign an ID (or a class, for multiple) to each of the desired elements ("p" and "textarea" in your case). Then use your ID/class to reference them for the show() or hide() methods, rather than navigating the DOM via parent(), sibling() and children().
Then your click handler will only need the line:
$('#idOfElement).toggle();

How to set jQuery mouseleave function for multiple divs with same id

I have a site that has multiple divs with the same id name. I want to set a mouseleave function for all of the divs that have this id. In my $(document).ready function I have this code...
$('#my_post_container').mouseleave(function(e)
{
hideSnippet();
});
My hideSnippet() function is correct, but doing this only set the mouseleave function for the first time that a div comes up of id my_post_container. Is there a way to set the mouseleave function to all divs with this id?
I have a site that has multiple divs with the same id name.
Then you need to fix that. You must not have more than one element with the same id. id values must be unique on the page.
You probably want to use class instead, at which point your code is basically fine:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
...although it coudl be shortened a bit if hideSnippet doesn't care what arguments it gets, doesn't care about this, and doesn't return false:
$('.my_post_container').mouseleave(hideSnippet);
It is invalid HTML to have multiple objects with the same id. As such, you cannot use normal selectors to find them all and you should fix your HTML to not do that.
The #1 suggestion is to fix the HTML so it does not have multiple objects with the same ID. Use a class name and you can then select them all with getElementsByClassName() or querySelectorAll() or with jQuery selectors as in:
$('.my_post_container')
If you insist on having multiple objects with the same id (a bad choice), then you will have to somewhat manually iterate over all possible objects that could have that id.
$("div[id='my_post_container']");
But, this is pretty darn inefficient because the browser can't use any of the built-in selector engine logic and it could break in the future if jQuery decides to optimize this. You really ought to switch to using class names.
You can not have multiple elements on the same page with the same id. Use a class instead, as shown here:
HTML:
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
jQuery:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
First of all there should not be any div elements with same ID name.. first we should solve that by keeping class name same.
then on mouse leave and enter part..
$(".testClass").on({
mouseenter : function() {
$(this).css({"background-color" : "blue"});
},
mouseleave : function() {
$(this).css({"background-color" : "green"});
}
});
this should work.. will add a js sample http://jsfiddle.net/meVc6/
and the same thing can be achived using css too..
just add css .testClass:hover { background-color:blue}

Possible to make div tags created using JQuery .html() clickable?

Hey guys bit of an odd questions but if I add div tags using JQuery .html() and give them an ID can I then use .click on them? The code might explain what I am trying to do. If not is there a possible work around?
I am trying to dynamically change my site without going to a new site.
So if I create Divs with an ID.
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
});
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
It does not work but I do not know why.
Thanks in advance.
No you would need .on() to be able to handle dynamic added elements.
$('#content2').on('click', '#button1', function() {
// do your stuff
});
Also note that you can only add a single element with a certain id to the DOM. In your example everytime when the element with id #funTime is clicked you add en element with the same id.
You could improve your code by adding the button with some class instead of an id to the DOM or having a counter to produce unique ids. Or by preventing other clicks on #funTime by using .one() depending on your needs.
You can only assign an event handler to an element that exists. So the assignment of handlers should be done after the creation of the elements:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
However, several calls clicks on funtime will result in several elements with the same id, which results in an invalid document. Either prevent duplicate ids (e.g. implement a counter) or use classes.
You can actually create elements, bind events to them, all before they are on the screen. Backbone and others to it this way too.
var myNewDiv = $("<div ...>");
myNewDiv.click(function(){});
$(something).append(myNewDiv);
If you want to add events to things that are not yet on the page you must you use jQuery delegate.
You should use an on() listener for dynamically added elements
$("#content2").on('click','#button1',function(){create();});
This will add a listener to check for live added buttons in the selected container (#content2)
To do add thehandler as elements are created would need to add it within the click handler right after elements are appended....otherwise need to use delegation methods like on()
This would work:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
/* elements exist can add event handlers*/
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
More common current practice is to use delegation that allows for future elements and can be run on page load

jQuery Hide using ID

I'm trying to change the border color of an image using its id with jquery
( photo['id'] is passed in from a previous function )
the ids of the photos are of the form 'photo239839'
$('#photo'+photo['id']+'').click(function(){
$('#photo'+photo['id']+'').css('border-color','#777');
});
When I try to use this same code using its class it works,
but I can't use this method since there are multiple images on the same
page with the same class
$('img.flickr_photo').click(function() {
$("this.flickr_photo").css('border-color','#777');
});
This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});
I would always always add a css class rather than an inline style.
Much more maintainable and extensible.
Example:
$('img.flickr_photo').click(function(){
$(this).addClass('greyishBorder');
});
Either photo['id'] is wrong, or is changing after you set up the click handler.
To test for the first case, you can alert (or console.log with FireBug, or whatever) the length of the jQuery selection:
alert($('#photo'+photo['id']).length);
The solution in the second case is to use 'this'. In the click handler, 'this' is set to the element that caused the click event.
$('#photo'+photo['id']).click(function(){
$(this).css('border-color','#777');
});
Edit: #Dreas Grech is right, as long as you want to apply the behavior to all the elements with the flickr_photo class. If you can generalize the selector to select all the elements with a single query, it's better to do that.

Categories