lightgallery does not work with dynamically generated elements - javascript

I have implement lighgallery plugin to my local site... and this is not working with dom elements ...
for example
1.) append dom element created with js to html code..
if i create something like this in js "<span id='imgcon'><img src="image"></span>" and this all code is in a varialbe lets call galleryview (var galleryview) and this variable i append to a div that is in html file <html><head></head><bdy><div class="container"></div></bdy></html> and append like this from js file code $(".container").append(galleryview); and in end i use this $(".imgcon").lightGallery(); does not work...
Here is jsfiddle demo not working with dom
2.) images are in html code
i have html code smthing like this <html><head></head><bdy><div class="container"><span class="imgcont"><img src="image"></span></bdy></html>
This works fine as it.$(".imgcon").lightGallery();
Here is jsfiddle working demo without dom.
Question : why i cannot use dom with lightgallery ?
First demo is not working becasue i use js dom and second demo is working because i use html code in html file.. or there any problem with my code..

Simply put your $(".imagecontiner").lightGallery(); inside the click handler
http://jsfiddle.net/o0y70kv0/1/
The above will work only for the first dynamically created gellery.
To make it work for multiple elements: pre-create in-memory appendable elements and assign to each the .lightGallery() instance
http://jsfiddle.net/o0y70kv0/6/
$(document).ready(function() {
var imagesarray = [
"http://www.planwallpaper.com/static/images/Winter-Tiger-Wild-Cat-Images.jpg",
"http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg",
"http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg",
"http://i765.photobucket.com/albums/xx291/just-meller/national%20geografic/Birds-national-geographic-6873734-1600-1200.jpg",
"http://www.gettyimages.com/gi-resources/images/CreativeImages/Hero-527920799.jpg"
];
var hiddenimages = "",
albumcover;
$("#appendnewcontainer").click(function() {
$("<span />", {
class : "container",
appendTo : $("#fotoappendarea"),
append : $("<span />", {
class : "imagecontiner",
html : "<a class='dfed' href=" + imagesarray[1] + "><img src='" + imagesarray[1] + "' class='_34'/></a>"
}).lightGallery()
});
});
});

when you generated gallery item after than you need to use below code in your project
var $methods = $('#gallery-container');
$methods.lightGallery();
$methods.data('lightGallery').destroy(true);
$methods.lightGallery({
thumbnail: true,
animateThumb: true,
showThumbByDefault: true,
});

Related

Attach different functions to dynamically created card

I have a card list that is being created by looping through some JSON data which is stored on Firebase. Each card is split in two parts: "overviewCardInfo" and "overviewCardOptions".
I would like to make it so that when the options part is clicked, a function is called (in this case a .toggleClass()) and when the info part is clicked, the title of that card is displayed somewhere else.
So far I have been unable to achieve either effect: The title of the card is nowhere to be seen and the toggleClass() either affects the div with class ".overviewCardOptions" or affects all cards rather than just the one clicked.
This is what the JSON array I am taking from Firebase to generate the cards looks like:
[{"name":"Push Ups", "duration":3, "break":3},{"name":"Squats", "duration":3, "break":3},{"name":"Running in Place", "duration":3, "break":3}]
JavaScript (some jQuery):
// Compile Routine Overview List.
var obj = JSON.parse(localStorage.exercise); // The JSON shown above
obj.forEach(function(exercise)
{
$("#overviewList").append("<li><div class='overviewCard'><div class='overviewCardInfo'>\n\
<h3>" + exercise.name + "</h3><p>" + exercise.duration + " sec.</p><p id='right'>Break: " + exercise.break + " sec.</p>\n\
</div><div class='overviewCardOptions'><img src='images/thrash.png' width='23' alt='' /></div></div></li>");
});
$(document).on("click", ".overviewCardInfo", function() // Attach event handler to document, as cards are generated after other elements on page.
{
$("#overviewSpecifier").css("display", "block"); // Works fine.
$("#infoP").text($(this).text()); // Shows all text contained in card, of course, how do I target the h3 tag specifically? jQuery API docs not helping me understand atm.
});
$(document).on("click", ".overviewCardOptions", function()
{
$(".overviewCard", this).toggleClass("toDelete"); // Fails.
});
HTML:
<ul id="overviewList"></ul>
<div id="overviewSpecifier">
<p id="infoP"></p>
</div>
Attach the click() event to the document instead to make it global.
$(document).on("click", ".overviewCardOptions", handleThrashClick);
Also, your object (in fact it's an array) shouldn't have quotation marks
var obj = "[ ... ]" should be var obj = [ ... ]
See demo here >> https://fiddle.jshell.net/9a457qzv/3/

Where do I put $(this) in the function?

Since I want to use classes instead of id's in these functions(I have three of the same function with different things I want to .append) I am sure I need to put $(this) in those functions somewhere to only trigger only ONE function on button click and not all three of them. but I am not sure because I am a total beginner in jquery/js, so I would appreciate some help.
$(document).ready(function () {
$(".onclick").click(function () {
$('#favorites').append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
http://codepen.io/anon/pen/JYxqEw - HTML And the Jquery Code
$('.onclick') selects all the elements with a class of onclick. That means that, whenever something with class="onclick" is clicked, that function will fire.
If you want all of those elements to append that exact HTML to the #favorites element, then you can leave your code as-is.
However, if what you're trying to do is append that html to the clicked element, that is when you'd use $(this) -- that selects the element you clicked with jQuery, then you can append directly to that element ie:
$(document).ready(function () {
$(".onclick").click(function () {
// this will append the HTML to the element that triggered the click event.
$(this).append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
EDIT
so to insert the contents of each .onclick into #favorites, you'll need to use the innerHTML value of the DOM node. example fiddle:
http://jsbin.com/qazepubuzu/edit?html,js,output
When you select something with jQuery, you're actually getting back not just the DOM node, but a jQuery object -- this object contains both a reference to the actual DOM node ([0]), as well as a jquery object ([1]).
So to select the DOM node with $(this), you target the node: $(this)[0]. Then you can use .innerHTML() to grab the HTML contents of the node and do as you like.
Final result:
$(function () {
$('.onclick').click(function () {
$('#favorites').append( $(this)[0].innerHTML );
});
});
So the building blocks are not that complex, but I think you're a novice jQuery developer and so you may not be clear on the difference between jQuery and JS yet.
$(selector, context) allows us to create a jQuery collection for a CSS selector which is the child of a current context DOM node, though if you do not specify one there is an automatic one (which is document.body, I think). Various functions iterating over jQuery collections make the particular element available as this within the JavaScript. To get to the strong element from the .onclick element in the HTML fragment you need to travel up in the hierarchy, then to the appropriate element. Then, we can collect the text from the element. We can do this in either JS or jQuery.
To do this with simply jQuery:
// AP style title case, because Chicago is too crazy.
var to_title_case = (function () { // variable scope bracket
var lower_case = /\b(?:a|an|the|and|for|in|so|nor|to|at|of|up|but|on|yet|by|or)\b/i,
first_word = /^(\W*)(\w*)/,
last_word = /(\w*)(\W*)$/;
function capitalize(word) {
return word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
}
function capitalize_mid(word) {
return lower_case.exec(word) ? word.toLowerCase() : capitalize(word);
}
return function to_title_case(str) {
var prefix = first_word.exec(str),
str_minus_prefix = str.slice(prefix[0].length),
suffix = last_word.exec(str_minus_prefix),
center = str_minus_prefix.slice(0, -suffix[0].length);
return prefix[1] + capitalize(prefix[2]) + center.replace(/\w+/g, capitalize_mid)
+ capitalize(suffix[1]) + suffix[2];
};
})();
$(document).ready(function() {
$(".onclick").click(function () {
var text = $(this).parents('.ui-grid-a').find('.ui-block-a').text();
var html = '<div data-role="main"class="ui-content">'
+ '<div class="ui-grid-b"><div class="ui-block-a">'
+ to_title_case(text) + '</div><div class="ui-block-b">More Info</div>'
+ '<div class="ui-block-c">Unfavorite</div></div></div>';
$("#favorites").append(html);
});
});

How to retrieve id from selected item using "this"

I am new at jQuery/javascript. I tried some suggestions I found on this forum but so far it did not help.
THis is what I am trying:
When loading categories from a database ( using ajax) this HTML statement is added for each category:
$("#Links ul").append('<li id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
Using F12 I see that the lines are correctly added.
E.g. <li id="cat3" data-catid="3">Seafood </li>
Next step is selecting a category in the screen and retrieve the products of this category using the value set for data-catid.
I have been told that I could "this.id" but so far no luck. Displaying the value of this.id with alert returns the correct value but for some reason I can't use it.
When I add (#cat3).attr(“data-catid”) in the code it works. But different options like these did not work:
("#cat"+ this.id).attr(“data-catid”)
(this).attr(“data-catid”)
var x = $(this).id();
var rest = x.substr(4, 1);
Everything with "this" creates error : Uncaught TypeError: ("#cat" + this.id).attr is not a function...
Trying to display any of these options does not give any output (not even a popup when I set an alert)
Any help would be appreciated!
You are loading dynamic values. Please use Event Delegation. And the $.one() binds the event once.
You need to add this in your ready function.
$(document).ready(function () {
$("#Links ul").one("click", ".cat", function(){
alert($(this).data('catid'))
});
});
To get the IDs of the elements, use $(this).attr("id") or $(this).prop("id") (latest jQuery) instead of this.id, as sometimes, it might return the jQuery object.
As you are creating elements like
$("#Links ul").append('<li class="cat" id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
create elements using jQuery
$("#Links ul").append( $('<li></li>', {
class: "cat",
id: "cat" + i,
data-catid: i,
text: categorie_tekst[1]
});
As you are creating elements dynamically use Event Delegation. You have to use .on() using delegated-events approach.
$(document).ready(function () {
$("#Links ul").on(event, ".cat", function(){
alert($(this).data('catid'))
});
});

execCommand insertHtml, outer div not inserted why?

Why is the DIV not inserted but only the IMG ?
$(document).ready(function() {
$(document).on('click', '#insertImage', function(){
/*
Why is the DIV not inserted ?
*/
var item = "<div class='resizable'><img src='http://www.rockiesventureclub.org/wp-content/uploads/2013/02/flower-icon.png'></div>";
document.execCommand('insertHTML', false,item);
})
});
see:
http://jsfiddle.net/daslicht/gU2jP/#base
Why not doing it with jQuery since you already use it??
http://jsfiddle.net/gU2jP/5/
var _$div = $('<div>'),
_$img = $("<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg' />");
_$div.append(_$img);
$('body').append(_$div);
The background of the Question was the following:
I just like to be able to make the added Image Float Left or Right.
Since jQueryUI automatically adds a wrapper-div around each resizeable item I thought that I need to add it somehow manually in order to assign a id to it.
doug65536 on Freenode helped me to create this solution without the need to create an additionally div manually:
We also discovered that the Fiddle wont work properly in safari
$(document).on('click', '#insertImage', function () {
document.execCommand('insertHTML', false,
"<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg'>");
$(".resizeable").resizable({
aspectRatio: true
}); //just a try here
$('#myImg').parent().css({
'float':'left',
'margin':'15px'
});
})
http://jsfiddle.net/daslicht/6cGbQ/
Thank you very Much !

How to simplify code to add new elements to a page with jQuery?

I've written the following code to add a clickable "link button" to a section of my page.
var linkButtonHtml = "<a data-makeId='" + makeId + "' href='javascript:expandMake(" + makeId + "," + categoryId + ")'>+</a> " + makeName;
var divHtml = "<div style='display:none' class='models' data-makeId='" + makeId + "'></div>" + "<br/>";
html += linkButtonHtml + divHtml;
$('#linkDiv').html(html);
The code works fine, but it's ugly and difficult to read with all the string concatenation.
As you can see, I am building anchor elements and div elements with string concatenation. The target of my anchor element is a javascript function invocation with two arguments. Is there a good jQuery way to improve the readability of this code?
I'm not sure if this really improves readability is here is a 100% jQuery solutions:
$(html)
.append(
$('<a />')
.attr('data-makeId', makeId)
.attr('href', 'javascript:void(0);')
.click(function(event)
{
// Prevent clicking the link from leaving the page.
event.preventDefault();
expandMake(makeId, categoryId);
})
.text('+'))
.append(
document.createTextNode(makeName)
)
.append(
$('<div />')
.addClass('models')
.attr('data-makeId=', makeId)
.hide());
Where "html" in $(html) is the html variable you have in your sample.
jQuery offers an option for a second argument when creating elements.
var linkButton = $('<a>',{'data-makeId':makeId,
href:'#',
click:function(){expandMake( makeId, categoryId )},
text:'+'
});
var div = $('<div>',{ style:'display:none',
'class':'models',
'data-makeId': makeId
})
.after('<br>');
$('#linkDiv')
.empty()
.append(html)
.append(linkButton)
.append( makeName )
.append(div);
EDIT: Fixed an issue where makeName was not appended.
Only real way is either abstracting some of your tag generation or spread the script out a little to make it more readable : http://jsfiddle.net/3dYPX/1/
Your also using jQuery so you might want to consider changing the way you trigger the javascript. Try looking into the .live() event. (Ill just get an example up, not that its very important)
Using live event for unobtrusive javascript:
http://jsfiddle.net/3dYPX/2/
It is all being done inside of the onLoad event at the moment, just to use as an example.
Use a template library such as
jQuery Templates instead of inlining
HTML.
Instead of using "javascript:" URLs, attach event handlers to the generated DOM fragments.
Refrain from using inline styles.
Something like:
$('#linkDiv')
.empty()
.append($.tmpl(myTemplate, {
makeId: makeId,
makeName: makeName,
categoryId: categoryId
}))
.click(function () {
var makeId = $(this).attr("data-makeId");
if (makeId) {
expandMake(makeId, $(this).attr("data-categoryId"));
}
});
Where myTemplate has the content:
${makeName}
<div class="models" data-makeId="${makeId}"></div>
Instead of using an inline style to initially hide the models, hide them all with a general CSS rule, and then selectively show them with a class:
.models { display: none }
.models.shown { display: block }
Just add the "shown" class to show a certain block of models.
Here you go:
$('#linkDiv').empty().append([
$('+').data('makeId', makeId).click(function(e) {
e.preventDefault();
expandMake(makeId, categoryId);
})[0],
$('<span>').text(makeName)[0],
$('<div class="models">').data('makeId', makeId).hide()[0],
$('<br>')[0]
]);
Live demo: http://jsfiddle.net/cncbm/1/
Consider this:
$('#linkDiv').data({'makeId': makeId, 'categoryId': categoryId}).empty().append([
$('+').click(expandMake)[0],
$('<span>').text(makeName)[0],
$('<div class="models">').hide()[0]
]);
So, you define that data-stuff on the parent DIV (the common parent) and you re-factor the expandMake function so that it reads those data-values from the parent DIV instead of passing them as arguments.

Categories

Resources