Jquery Javascript best way to check elements done appending - javascript

I have a list of elements that are dynamically appended after an Ajax call. I am using a plugin that creates a lightbox click event for the anchors dynamically appended. It works fine except sometimes it says that the title is undefined. I realize this is because the plugin gets initiated before the title attribute is completely done appending to the DOM. I know of several ways to do this, but what is the BEST way to check that all these elements are completely appended?
Ajax call is already made and data parsed with this function (colorbox title is the one that evaluates to 'undefined' for only some):
function pageImages(images,_q){
for(var i = 0; i < images.count; i++){
$('#pageImages').append('<div class="pageImageItem"><a href="' + images.data[i]._clickurl + '" title= "' + images.data[i]._title + '">\
<img src="' + images.data[i]._thumbnailUrl + '" alt= "' + images.data[i]._title + '"/>\
</a><div class="hoverInfo"><h2>' + images.data[i]._title + '</h2><p>' + limitCharacters(images.data[i]._clickurl,40) + '</p></div></div>');
}
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
}
And here is a picture of what is happening (anchor highlighted is the element that clearly has a title attribute but is showing undefined in lightbox):

You can wrap the jQuery element find block in a timeout without timevalue. The timeout will wait for all javascript to be finished with all processes. Example:
window.setTimeout(function() {
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
});

Related

How can I get attributes from dynamically created buttons?

So, I am building some sort of e-commerce website and I needed to import a bunch of products from a mysql database, using nodejs and ajax.
I've been able to get that so far, aswell as creating certain buttons below each product that will lead to a /product page where additional information will be displayed of that exact product.
Since those buttons were not dynamic, I had the need to add an attribute, which will contain the products ID, which I will then use to send a POST request to the server so I can get the information about that specific product.
And although I was able to add the attribute to the buttons themselves, I have no idea how to get their value.
This is how I added my attributes to the buttons.
$(function () {
$.ajax({
type: 'POST',
url: '/getPacotes',
success: function (data) {
for (var i = 0; i < data.length; i++) {
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
var precoPacote = data[i].Preco_Pacote;
var fornecedorPacote = data[i].Fornecedor_Pacote;
var foto = "https://webitcloud.net/PW/1617/RMR/Views/images/Pacotes/" + data[i].Foto;
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<img src=" + foto + " alt='Mountain View' style='width:150px;height:150px;'><br><br><input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
$("#pacotes").append(pacoteSet1 + "<h1>" + nomePacote + "</h1>" + "<h2>" + fornecedorPacote + "</h2>" + "<h3>" + precoPacote + "euros/mes </h3>" + pacoteSet2 + pacoteSet3);
$(document).find("#btnPac" + i).attr({
"idPacote": idPacote
});
}
}
});
});
And this is how I was trying to get their attributes
$("button").each(function () {
console.log(this.idPacote);
$.post("http://localhost:3000/pacote?id=" + this.idPacote);
});
But it doesn't seem to work
idPacote returns undefined and I have no idea why, because I simply give the buttons an "id" and replace the idPacote with the "id" itself, it will return the buttons ID
Sorry if the question sounds dumb. I am not very experienced in these matters.
When you are using jQuery I would suggest you to use the HTML5 data attribute in order to set a specified attribute to a HTML element:
<button data-id="1"></button>
You can set and access it using jQuery:
$('button').data('id', value); //set data-id
$('button').data('id'); //Read data-id
Furthermore change
<input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>
to
<button name='comprar'>Comprar Pacote</button>
in order to get elements from $('button')

Getting the id of an html on mouseover with only javascript (no jquery)

My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";

javascript function using jquery addClass() method does not add class

The script works, creates everything correctly, etc., but the jquery addClass method isn't adding the class. I'm new to using jquery methods in a javascript function, any help is appreciated, including alternate methods for adding the appropriate classes without using jquery.
function thumbnail(Img, Element, Modal, ModalTitle) {
"use strict";
/*jslint browser:true*/
/*global $, jQuery*/
//this function will append an anchor tag with the appropriate functionality, accepting inputs on the image filename, attaching element, and modal
//Img = full filename in format of foo.png
//Element = the ID of the element within which the thumbnail anchor will be placed
//Modal = the ID of the modal
//ModalTitle = Text used for title of the modal and title of the caption
var image, element, modal, loc, output, iUrl, modal_loc, modal_output, mtitle;
image = Img;
element = Element;
modal = Modal;
mtitle = ModalTitle;
iUrl = "/design-library/images/thumbs/" + image;
output = "<a href='#' data-reveal-id='" + modal + "'>";
output += "<img class='sample_img' src='" + iUrl + "' alt='" + mtitle + "' />";
output += "</a>";
output += "<p class='caption'>" + mtitle + "</p>";
modal_output = "<h1>" + mtitle + "</h1>";
modal_output += "<img src='" + iUrl + "' alt='" + image + "' /><a class='close-reveal-modal'>×</a>";
//create the modal container
$(modal).addClass('reveal-modal');
modal_loc = document.getElementById(modal);
modal_loc.innerHTML = modal_output;
//the end of the script gets the element and adds the anchor tag that exists in output
$(element).addClass('samples');
loc = document.getElementById(element);
loc.innerHTML = output;
}
Since modal and element are IDs, you should correct your selectors to use them as ones:
$('#' + modal).addClass('reveal-modal');
$('#' + element).addClass('samples');
Side note. Once you have found the DOM element with jQuery, there is no need to perform the second search with getElementById:
var modal_loc = $('#' + modal);
modal_loc.addClass('reveal-modal');
modal_loc.html(modal_output);
if modal is an ID string, you need to do:
$('#'+modal).addClass('reveal-modal');
Try changing:
$(element).addClass('samples');
to
$('#' + element).addClass('samples');

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

selection error in jquery with dynamic elements

First of all thanks for reading. I have a problem with jQuery. I am trying to get some data with AJAX and put the result on page with dynamically created div. This works perfect. The problem occurs when I try to select the created div and do something with it
$('.myNewDiv').css('border', '2px solid #000080');
It gives me error in jQuery library
In Chrome debugger it is "Uncaught TypeError: Cannot read property 'slice' of undefined" on line 2234
And in Firebug under firefox "Array.prototype is undefined Line 3324"
I have no idea what is the problem so i'd be grateful for any information
The whole function code:
function AddNextDiv(number) {
var url2 = '<%= ResolveUrl("~/Translate/GetLineDetails") %>';
$.getJSON(url2, { textLineID: LinesIDs[number], TranslatedSubsID: '<%= Html.Encode(Model.OutputSubs.SubsID) %>' }, function (result) {
if (result == "Already in Database") return false;
var myObject1 = JSON.parse(result);
$("#MainField").append("<div class=\"TextLineDiv\">This is line number " + myObject1.LineNumber + " of 423<br/>" + myObject1.TextValue + "<br/><input id=\"TranslationBox" + myObject1.LineNumber + "\" class=\"translationTextBox\" type=\"text\" size=\"20\" /><br/><div id=\"CheckBoxDiv" + myObject1.LineNumber + "\"><input name=\"" + myObject1.LineNumber + "\" class=\"addCheckBox\" onchange=\"HideDiv(this)\" type=\"checkbox\" /><br/><div class=\"NumberDiv\" title=\"" + myObject1.LineNumber + "\" onmouseover=\"CallRefresh(this)\" > This line was translated <div id=\"Translated" + myObject1.LineNumber + "\">" + myObject1.TimesTranslated + "</div> times.</div><br/><br/></div></div>");
$("div#MainField div.TextLineDiv").css('border', '2px solid #000080');
return true;
});
}
`
You can't select things that aren't added to the document yet. If you can restructure your code so that the div can be caught into a variable it would be easy. Otherwise you need to do something like add it to a hidden element then select it. (yuk!)
I suggest using jQuery's DOM tools rather than building everything as a big string of html.

Categories

Resources