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');
Related
I am trying to find and append some text in a dynamically created parent div
but its not working.
Here is what I have tried.
var mainDiv = "" +
"<div>" +
"<div></div>" +
"<div>" +
"<div class='image-here'></div>" +
"</div>" +
"</div>"; // proper script is in Fiddle
var imageDiv = $(mainDiv).children(".image-here");
$(imageDiv).html("text allocated");
$(mainDiv).dialog();
Here is the Fiddle: http://jsfiddle.net/xBB5x/10166/
Change this:
var imageDiv = $(mainDiv).children(".image-here");
$(imageDiv).html("text allocated");
$(mainDiv).dialog()
to this:
$(mainDiv).dialog().find(".image-here").html("text allocated");
Here is the JSFiddle demo
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 + "')>";
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) + '';
}});
});
I am working on this pen.All I want to do is if there is no image in the post then default image should be shown.The Jquery I've used is
$(function () {
$(".post").each(function () {
var posthead = $(this).find("h2.post-title").text(),
postlink = $(this).find("h2.posttitle a").attr("href");
if($(this).find("img:first")>=1){
var imageSrc=$(this).find("img:first").attr('src');
}
else{
var imageSrc="http://3.bp.blogspot.com/-P5H7BaGibPg/UjVD-0SIs9I/AAAAAAAADFk/l65svtw9IHg/s320/70-photography-2.jpg";
}
$(this).replaceWith("<div class='post'><img class='thumb' src='" + imageSrc + "'/><div class='posthead'><h2 class='hometitle'><a href='" + postlink + "'>" + posthead + "</a></h2></div></div>");
});
});
According to above if there is an image then its attribute src should be as a var imageSrc but if it is not else condition having a image should be as var imageSrc.
If you want to check if an image is present you need the length property of the jQuery object
Replace
if($(this).find("img:first")>=1){
for
if($(this).find("img:first").length>=1){
Here's the updated codepen
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);
});