Fade Out parent element of a link which was appended (with jquery) - javascript

I've got an empty div and I'm appending some text with html and two links in it. One link is normal with an href="some url" and the other is an element with a class. In short: this is a "yes | no" block. Yes is a normal url and NO is an element which will fade out the entire div.
The problem is that my div isn't fading out.
HTML:
(with css: display: block for hidding it from start)
JS:
// THE TEXT
var lbText = 'Thanks for helping us! Here\'s a preview of the part of gelattina you\'re about to take.';
lbText = lbText + '<br /><img src="img/g10/OldGelattina'+cpNum+'.jpg" />';
lbText = lbText + '<br /> YES | NO'
// I USE THIS CODE TO APPEND THE TEXT AND FADE IN THE ENTIRE DIV
$('.not-claimed').bind('click',function(){
$('#lightboxcont').empty().append(lbText).css({
'width': '30%',
'height': '30%',
'background': '#ffffff',
'zIndex': '9999'
}).fadeIn().center();
$('#lightboxOverlay').fadeIn();
});
The next code is what I'm using to hide de entire div
$('#lightboxcont a').bind('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
As I said, the problem is that the last jquery code isn't working and I don't know why.
I hope you understand, sorry for my english.

Jquery's bind method only is attached to matching elements that are available at the time it was first called. But they include the 'live' method which attaches to all matching elements now and that are created in the future. So if your appending the html after you bind the event try using:
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
Change bind to live. http://api.jquery.com/live/

Are you trying to attach the event to the <a> tags before you add them to the DOM? If you were to call that "next code" from inside the .not-claimed click event, after the append, it will probably work
Does your "click" function ever get executed?

Change bind to live. Bind won't work for dynamically added elements.
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});

Thanks guys!!! the thing was solved using live instead of bind... I'm really really thankful!
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
Greetings!!

Related

append onclick function to div jquery

I'm trying to add an on click function to a div using these lines of code but the click event doesnt trigger the alert.
var str="<script>$(this).on(\"click\",function(){alert('hello');})";
str+="<";
str+="/script>";
$("div:contains('Send')").last().append(str);
I've also tried this and $(this)[0] but these give me the error this.on/ $(this)[0].on is not a function
I don't know what Im doing wrong and would appreciate any and all help on the matter.
Shouldn't have to go through the trouble of creating strings for script. You can just use jquerys .on and register it with a click event.
$("div:contains('Send')").last().on("click", function () {
alert('hello');
})
If you are using jQuery, you can add click event to all the div by using $("div") for selector (just remember to call the function after you load the div)
I have create an example of simple click function
$(".start").click(function() {
$(this).toggleClass("onClick");
})
http://jsfiddle.net/7j6s2Lws/2/
The $(this) will identify which object is actually trigger the event, and choose it only. In my case, if you click on a div, it will change color (of it and only it)
i would choose a slightly different approach. i hope i understood your problem right even though i dont really get what you want to achieve by putting <script> into your string here... maybe this helps:
html
<div id='container'>
<button>Send</button>
</div>
js
var $container = $("div:contains('Send')");
var elementToAppend = "<div class='myClass' style='width:100px; height:100px; border: 1px solid red'>added dynamically ... click me</div>";
appendToContainer($container, elementToAppend);
$('.myClass').click(function($element) {
alert(123);
});
function appendToContainer($container, element) {
$container.append(element);
}
fiddle
http://jsfiddle.net/2pofLnb7/2/

jQuery: create a div alert you when its is clicked,

I can't put a title to it. It's inception :)...
I have add div, when it is clicked, it creates alert div. When alert div is clicked it alert me.
that is an example.
$("#add").click(function(){
$("#add").after("<div class='alert'>Alert</div>");
});
$(".alert").click(function(){
alert("Here I am");
});
I noticed if I placed a div in the html template as <div class="alert">Alert</div> the alert will work. But if I added the div through the jQuery/JS it will not work.
what is the point of that?
to add more inputs and remove it in case he/she added too much, I noticed it didn't work and I wanted to know why:
this is the actual code:
$(document).ready(function(){
var i = $("#new_field_count").val();
//add new field
$("#addnew_field").click(function(){
i++;
$("#new_field").before("<div class='fivepadding'><input name='part1_" + i + "' type='text' placeholder='<?=lang('addform_p1')?>'> = <input name='part2_" + i + "' type='text' placeholder='<?=lang('addform_p2')?>'> <span class='remove clickable'><?=lang('addform_field_remove')?></span> </div>");
$("#new_field_count").val(i);
});
// remove the field
$(".remove").click(function(){
i--;
$(this).parent('div').remove();
$("#new_field_count").val(i);
});
});
For dynamically created content, use on.
$("#wrapper-div").on("click", ".alert", function(){
alert("Here I am");
};
Additionally, it's worth mentioning that it is adviced to use on instead of clickfor monitoring for example classes.
Rather than adding an event handler to every class element separately, the click event will bubble to the parent. According to the jQuery docs, it is a good idea to attach the handler to the closest relevant parent element (rather than the document).
Your document.ready block is interpreted once the DOM has finished loading. At that point in time, anything not in your DOM cannot have proper event binding. Here you can use delegation to make sure your bindings are going as planned. Since your 'body' will be loaded, you can target your .alert div for clicks as follows:
$("body").on("click", ".alert", function(){
alert("Here I am");
};

click event not working jQuery

I am trying to handle the click event using jQuery
on upload success, I am creating the following using jQuery:
$("#uploadedImage").append( "<div class='img-wrap'>
<span class='deletePhoto'>×</span>
<img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
</div>
<span class='gap'></span>");
and for handling click event for the above created div's I have written this:
$('.img-wrap .deletePhoto').click(function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.
Any help or suggestion would be a great help.
Thanks in advance
delegate the event and change as suggested:
$("#uploadedImage").on('click', '.deletePhoto', function() {
You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.
although $(document) and $(document.body) are always available to delegate the event.
It is better to use on() when you create new element after DOM has been loaded.
$(document).on('click', '.img-wrap .deletePhoto', function() {
});
You are creating your element dynamically that is why you would need .live()
but this method is deprecated in newer version.
if you want to use jquery 1.10 or above you need to call your actions in this way:
$(document).on('click','element',function(){
`your code goes in here`
})
try this:
$(".img-wrap .deletePhoto").on('click', function() {
});
You can change a little in your code.
$(".deletePhoto").off("click").on("click",function(){
//Your Code here
});
First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.
And Also check css of your element (height and width) on which you are clicking and yes
$(document).on('click','Your Element',function(){
//your code goes in here
});
Will works fine
use delegate:
$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
see details delegate and .on here

Dynamically generated html elements stop working

In the following code I have some comments in an array which are displayed in a div using jQuery. Each comment has an options button which works fine until I post a new comment. I tried using unique IDs for each element but it didn't work either.
When the page loads, the options buttons work; but when I submit a new comment, none of the buttons work. What am I doing wrong?
Here's my script:
var i = 0;
var comments_display= "";
var comments = ['Hello World!', 'Hello! This is a comment.'];
//reads the entire array, creates the content, and sends it to the div
function show_comments(){
for (i=0; i<comments.length; i++){
comments_display += "<div class='single_comment_container'>";
comments_display += "<div class='comment_comment'>" + comments[i] + "</div>";
comments_display += "<div class='options'>Options</div></div>";
}
$("#comment_container").html(comments_display);
comments_display = "";
}
//appends a new comment to the array
function new_comment(){
if ($("#comment_input").val() == null || $("#comment_input").val() == ""){
alert("Your comment must be at least 1 character long.");
}
else{
comments.push($('#comment_input').val());
show_comments();
$("#comment_input").val("");
}
}
$(document).ready(function(){
show_comments();
$("#submit_comment").click(function(){
new_comment();
});
//display a message when an element of the class 'options' is clicked
$(".options").click(function(){
alert("OPTIONS");
});
});
And here's a fiddle to see how it works. http://jsfiddle.net/fahKb/3/
Thank you for taking your time to read this question.
You need to use delegation:
$(document).on( 'click', '.options', function() {
alert("OPTIONS");
});
http://api.jquery.com/on/
Note: You might want to use a static element other than document. (Some parent div that's always on the page or something.)
Just because you are adding elements dynamically so click won't work on those, so you have to find the closest existing parent on the page, here in your case is this comment_container and use the .on() handler: http://jsfiddle.net/fahKb/4/
$('#comment_container').on('click',".options",function(){
alert("OPTIONS");
});
$(document).on( 'click', '.options', function() {
alert("OPTIONS");
});
This first response is right, the cause of this is that when elements are loaded into the DOM you assign event listeners. Essentially saying hey if this is 'clicked' then do something. The problem is that when adding a new element you have NOT also added the event listeners. By doing something like the above code, essentially what you're doing is a search for everything within document that then has the class of ".options" and finally if it is clicked then acting and executing some code.
With that said using document isn't the most optimum method but it is sometimes necessary. A better solution would be if you were to wrap all the comments in say a "div" or some other element then pass that in place of document. This will instead of searching the entire document for the '.options', it would only search your wrapper eliminating alot of unnecessary work.
$('.commentWrapper').on( 'click', '.options', function() {
alert("OPTIONS");
});

Trying to toggle a panel whilst changing the icon to 'view more' and 'view less'

I've just started learning jQuery/javascript, so this might seem like a really basic question, but it's annoying me nevertheless.
I have a panel of 6 <li>s, 3 of which are hidden until clicking on the 'view more' link at which point the panel toggles to reveal the other 3. The icon is changing from 'more' to 'less', but then not changing back to 'more'. Can anyone see the problem in the code?
Any help would be greatly appreciated :)
Thanks,
David
$(document).ready(function() {
$('.allApps').hide();
$('.moreAppsIcon').click(function() {
$('.moreAppsIcon').removeClass("moreAppsIcon").addClass("lessAppsIcon");
$(this).toggleClass("active");
$('.allApps').slideToggle("slow");
return false;
});
$('.lessAppsIcon').click(function() {
$('.appsMore').slideToggle("slow", function () {
$('.appsMore').removeClass("appsMore").addClass("moreAppsIcon");
$(this).toggleClass("active");
return false;
});
});
});
It's easier to use .live() here, like this:
$('.moreAppsIcon').live('click', function() {
//and...
$('.lessAppsIcon').live('click', function() {
Otherwise your functions aren't being bound correctly. For example $('.lessAppsIcon') finds elements with that class at that time and binds a click handler to them...elements getting that class later don't get that click handler, whereas .live() works on the selector of the element at the time of the event, having the result you want.
So basically you're attaching n event handlers, one for each element matching initially...when you do .addClass() the other elements don't get that event handler all the sudden, it's on the DOM elements you initially found, not dynamically added to others when they change class. For the same reason .removeClass() doesn't remove the event handler. However, if you use .live() like above, it'll have the effect of changing event handlers like you're after.
I figured it out. It was pretty much what Nick was saying actually to do with the time of the event. I added an id to the <li> to handle the click event. This is what it looks like:
$(document).ready(function() {
$('.allApps').hide();
$('#moreOrLess').click(function() {
$('.allApps').slideToggle("slow", function() {
$('#moreOrLess').toggleClass("moreAppsIcon").toggleClass("lessAppsIcon");
$(this).toggleClass("active");
});
return false;
});
});
Cheers for the help though Nick :)

Categories