Trying to hide() an element with jQuery - javascript

I have code that does this:
$('.attachment-medium').each(function(){
$(this).click(function(){
var gallWidth = $('.gallery').width();
$('.gall-output').toggle().css('width', gallWidth);
var url = $(this).attr('src').slice(0,-12) + '.jpg';
$('.gall-output-img').html('<img class="img-responsive" src="' + url + ' "/>');
var imgMeta = $(this).parent().next().html();
$('#gall-output-meta').html(imgMeta);
});
});
This generates a modal overlay and displays an img withing a div with class .gall-output. I've created a small <p class="gall-close">close</p> to hide() the .gall-output but it doesn't seem to be working with this code:
$('.gall-close').click(function() {
$('.gall-output').hide();
});
Is there a way of using this .gall-close to hide or toggle .gall-output?
Thanks for your help.

In case the .gall-close is added later and not in the dom when the page is loaded, you can attach the click-event using event-delegation:
$(document).on("click", ".gall-close", function(){
$('.gall-output').hide();
});
Instead of $(document) any static parent element can work as container element to delegate the event. In case this solves your issue, you can check https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

Related

javascript click event not firing action

On page load, I have a search box that, once used, populates a div with multiple images. The javascript from the search uses this function to append all images into the div
function appendSomeItems(url, id, name, style) {
return '<div><div class="md-card md-card-hover"> <div id="getImage" class="gallery_grid_item md-card-content"> <img class ="uk-align-center imageClick"></a> <div class="gallery_grid_image_caption"> <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
}
This works perfectly. Now I'm trying to make it so that when I click any one of the images it triggers an action (in this case a console log)
$('.imageClick').click(function handleImage() {
console.log(good);
});
However, it does nothing. No error but no console log.
What am I doing wrong here?
You need to use event-delegation in order to bind an event to dynamically created elements:
This approach uses document as the parent element, however, a good practice is to use the closest parent element.
$(document).on('click', '.imageClick', function handleImage() {
console.log(good);
});
Try with .on() to attach event on dynamically created element. This will allow attaching the event to the elements that are added to the body at a later time:
$('body').on('click', '.imageClick' function handleImage() {
console.log(good);
});
The problem is that you are calling $(".imageClick").click() before you dynamically create the items.
This means that jQuery doesn't actually bind the click listener to the items, since when $(".imageClick").click() is run, the elements don't actually exist yet.
Try this:
$("body").on("click", ".imageClick", function handleImage() {
console.log("good");
});
Also see this post for more information: In jQuery, how to attach events to dynamic html elements?

JS delegate unique event (one()) for dynamic declared elements

I'm working on js-project. Some parts of HTML is generating via JS like this:
html += '<div class="button"><a href="' + url1 + '>' + button_text1 + '</a></div>';
html += '<div class="button"><a href="' + url2 + '>' + button_text2 + '</a></div>';
What I want is create listener to the first click for each of the buttons.
Idea 1: Use $(.button a).live('click', doSomething) because of dynamic declaration. Sadly, there's no way to force trigger only on the first click like that. Also deprecated.
Idea 2: Use $(.button a).one('click', doSomething). Not working because of on() might fail to find selector when DOM is ready, but still rendering ($(document).ready(...)). See details here: https://jqueryhouse.com/jquery-on-method-the-issue-of-dynamically-added-elements/
Idea 3: Use $(body).one('click', '.button a', doSomething), i.e. delegate event as noted source suggests.
But it seems like JS is read it not as "Here is an array of elements; for each element add one('click') event", but as "Add one('click') event for click on any element from an array", because an event is triggered only once no matter what button I have clicked.
I was really trying to find any clues to how manage this situation but got no luck. I will be really grateful for help or another idea how to solve this!
«I want is create listener to the first click for each of the buttons.»
The keyword here is each.
Try that:
$(.button a).each(function(){
$(this).one('click', doSomething); // (!)No prenthesis here... Just the function name.
});
Documentation for the .each() method.
Since you append new elements dynamically... After you appended html to a container, run a similar each loop on them like this:
// Assuming you do this
$(".container_selector").append(html);
// Then run the each loop
$(".container_selector").find(".button a").each(function(){
$(this).one('click', doSomething); // (!)No prenthesis here... Just the function name.
});
You are overthinking things. So use event delegation and some flag that says if it has run or not.
$(document).on('click', '.test', function() {
var elem = $(this) // what was clicked
if (elem.data('clicked')) { // see if we clicked it
return false // if yes, ignore the click
}
elem.data('clicked', true) // mark it was clicked
elem.html((new Date).toLocaleString()) // do something
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
Or go off a class that has not run and remove it
$(document).on('click', '.test-run', function() {
var elem = $(this) // what was clicked
elem.removeClass('test-run') // remove class so will not be clickable
elem.html((new Date).toLocaleString()) // do something
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test test-run">1</div>
<div class="test test-run">2</div>
<div class="test test-run">3</div>
<div class="test test-run">4</div>

target a button inserted by ajax with javascript

hello i'm inserting this image with a button by ajax when visitor upload an image
for (var i = 0; i < data.length; i = i + 1) {
imageThump += '<img src="' + data[i].path + '" />';
imageThump += '<button id="edit-details" type="button" class="btn btn-info">Edit Details</button>';
}
$('#uploaded-images-thumb').append(imageThump);
i want to target the button with javascript but it keeps failing ???
$('#edit-details').on('click', function(){
console.log('clicked');
});
You need to deal with dynamic event (aka live event). As the button injected into DOM after DOM load.
$('body').on('click', '#edit-details', function(){
console.log('clicked');
});
NOTE: instead of body, should bind to its closest non-dynamic parent element.
If your #uploaded-images-thumb is non-dynamic then better to bind against it. like:
$('#uploaded-images-thumb').on('click', '#edit-details', function(){
console.log('clicked');
});
For more detail check .on()
You need to delegate the event, because when you inserted your event handlers, the element was not present:
$("body").on('click', '#edit-details', function(){
console.log('clicked');
});
So we have selected body, which is a static tag and delegate the events inside them. Also, as a side-note, it is better to bind the event to the closest static parent and not the absolute parent, which is the document or the body.
In your example, it could be like:
$("#uploaded-images-thumb").on('click', '#edit-details', function(){
console.log('clicked');
});
Exactly what was mentioned above is the answer. Essentially the element doesn't possess the same events (click) as the existing DOM elements, so when it's dynamically generated you don't have access to the needed events for the new element.
To expand on what the other posters have mentioned, Here is a small example of the structural idea.
<div id="element-wrapper">
<button class="my-btn">Existing Button (has event)</button>
<button class="my-btn">Existing Button (has event)</button>
<button class="my-btn">Just Dynamically Added to DOM!!!</button>
</div>
This code below will work for all the buttons except the last one:
$('.my-btn').click(function() {
alert('Clicked!');
});
This code below will work for ALL buttons (since '#element-wrapper' is not dynamic):
$('#element-wrapper').on('click', '.my-btn', function() {
alert('Clicked!');
});

jQuery dialog is not working for element created dynamically

I am working with jQuery dialog. I have one problem that trying to solve that is:
I have created the dialog on click of of anchor class and its working. Than after this I have created one more anchor tag with same class and on click of that new created tag dialog is not working.
Here is html:
<div id="loader_ajax"></div>
<a id="show_hide_window1" class="show_hide_window" href=""> Dialog </a>
<div class="next_tg"></div>
Here is jQuery code:
$(function(){
$(".show_hide_window").click(function(){
showDialog();
});
$('.next_tg').html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
});
function showDialog()
{
$("#loader_ajax").dialog({ modal: true, height: 400,width:650,title: title });
return false;
}
I have already tried with delegation(Event binding) its not working. For Dynamically created anchor it give error in console: TypeError: $(...).dialog is not a function
Please help!! Thanks
You can currently binding click event to elements that are present in the DOM when binding code executes. You need event delegation for dynamically created elements. You also need to add the newly create element to DOM, suppose you want to add to loader_ajax
Here static parent could be any html element, in your case it would be loader_ajax
You code would be
$("#loader_ajax").on("click",".show_hide_window", function(){
showDialog();
});
var newTextBoxDiv = $(document.createElement('div'));
newTextBoxDiv.html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
$("#loader_ajax").append(newTextBoxDiv);
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
Use on Event. This will manage dynamically added elements.
$(function(){
$('body').on('click', '.show_hide_window', function() {
showDialog();
})
$('.next_tg').html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
});
Fiddle : http://jsfiddle.net/fqt0yztb/
Reference : In jQuery, how to attach events to dynamic html elements?
I have make it from my own code. Now dialog successfully working for dynamically created element.
fiddle
$(document).on('click', '.show_hide_window', function (evt) {
var dialog = $('<div></div>').append('<img src="../images/themeroller.gif"/>');
var getContentUrl = $(this).attr('href');
dialog.load(getContentUrl + ' #content').dialog({
title: $(this).attr('title'),
modal: true,
height: 400,
width:650
});
dialog.dialog('open');
return false;
});

Onclick event on dynamic created anchor tag

I have an anchor tag which created dynamically and this anchor tag has an onclick event like this:
$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>" + "<a href='javascript:void(0)' onclick='deleteEducationLevel(" + educationHistoryId + ");'>Delete</a>");
when I click on this anchor I got js error saying:
TypeError: 'click' called on an object that does not implement interface HTMLElement.
I suspect some character escaping issue but unable to resolve.
Added
generated html:
<div id="ff8081814734be020147357beda5002b"><span>A Level</span><a onclick="deleteEducationLevel(ff8081814734be020147357beda5002b);" href="#">Delete</a></div>
Try replacing that line with the following, so that the event is bound like this:
var $link = $("<a href='javascript:void(0)'>Delete</a>");
$link.on("click", function() {
deleteEducationLevel(educationHistoryId);
});
$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>").append($link);
In my (very reduced) test, this seems to work: http://jsfiddle.net/E7LRt/
Is there an actual need to do this with just one line?
I'd suggest the following solution:
var $anchor = $(document.createElement("a")).attr("href","javascript:").text("Delete").on("click",function() {
alert("clicked!");
alert("educationHistoryId: " + educationHistoryId);
});
$("body").append("<span>" + degreeTitle + "</span> ",$anchor);
This works great: Fiddle
I always try to prevent using inline eventhandlers. It's bad practise in my opinion.
Give the span a class and use event delegation.
You can then bind the click event to a existing parent(I am assuming element with id= "#"+educationHistoryId is existing when the event handler attachment takes place) and then delegate the event to the newly added link.
$("#"+educationHistoryId).on("click", <class>, function(){
deleteEducationLevel(educationHistoryId);
});

Categories

Resources