I have an 'a href' that is a title.
Vendor1 product title
I want to display an image based on the first word of the title.
Vendor1 product title
<div class="logo"></div>
Vendor2 product title
<div class="logo"></div>
Vendor3 product title
<div class="logo"></div>
These are item cells and they use the same template to be generated so the classes are always the same. There are many of them.
The script I have so far is working but only for the first product in the list (shows correct logo).
function getlogo() {
var string1 = document.getElementsByClassName('title')[0].innerHTML;
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
document.getElementsByClassName('logo')[0].innerHTML = '<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">';
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
}
getlogo();
I've looked around but sure how to loop this or even if that is the solution.
http://jsfiddle.net/W7bm5/
It's easy if you use jQuery each function.
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
$(this).html('<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
or you can do it with the pure javascript, but put your logics in a loop, with [0] replaced to the loop index.
Update - here's how to keep the current text links:
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
var html = $(this).parent().html();
$(this).parent().html(html + '<br /><img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
You could use a for loop to run through the code you have for a different index of the getElementsByClassName results. See your jsFiddle
You could also ditch the getElementByClassName, which I think has spotty support in some browsers and isn't especially good performance, and navigate the DOM using JavaScript if your structure is always the same, or even jQuery if you'd like a library to make it easier.
But by far the best is if you did it when it was generated in the first place. How are you generating the code and could you not use that to achieve what you are trying to achieve?
Related
I may want to display different versions of charts of the SAME stock symbol so it needs using "var".
(Other uses I have are weather charts or traffic cams etc, so I have broader applications).
I'll illustrate it with stock charts.
By trial and error I found using the id="x" and "document.getElementById" works,
but it needs careful bookkeeping of the SAME and unique id TWICE on each line. (Breaking the line instead of a "long line" makes it even harder to keep id's straight)
Imagine with dozens of additional lines of chart variations it becomes tedious.
Is there a better way? How would you code it to produce a "collage of graphs"?
<script> var sym = "MSFT" </script>
<h1><strong> <body> Symbol <script> document.write(sym); </script></body><br>
<img src="" id="i1">$ <script> var a = document.getElementById('i1'); a.src = "http://www.google.com/finance/chart?cht=o&tlf=12h&q=" + sym ; </script>
<img src="" id="i2">% <script> var a = document.getElementById('i2'); a.src = "http://www.google.com/finance/chart?cht=c&tlf=12h&q=" + sym ; </script>
<!-- etc. perhaps dozens more different charts for the same symbol -->
I would remove all of the <script> tags from inside the HTML. This keeps document structure and behavioral logic separate. Here's an example using a loop and string concatenation that should be expandible:
<h1 id="title"></h1>
<img src="" class="symbol" alt="stock chart">$
<img src="" class="symbol" alt="stock chart">%
<!-- etc. perhaps dozens more different charts for the same symbol -->
<script>
const sym = "MSFT";
const urls = [
"http://www.google.com/finance/chart?cht=o&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=c&tlf=12h&q="
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symElems = document.getElementsByClassName("symbol");
for (let i = 0; i < symElems.length; i++) {
symElems[i].src = urls[i] + sym;
}
</script>
You might want to use an object instead of an array for the URLs, and add ids to your <img> tags depending on your needs. The problem with not using a class name is that it might be easier to lose track of how many elements are in the collection you're manipulating (not to mention styling). You may also wish to dynamically generate the <img> elements using document.createElement("img") and set the properties in JS:
<h1 id="title"></h1>
<div id="sym-container"></div>
<script>
const sym = "MSFT";
const urls = [
"http://www.google.com/finance/chart?cht=o&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=c&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=g&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=s&tlf=12h&q="
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symContainer = document.getElementById("sym-container");
urls.forEach(e => {
const symElem = document.createElement("img");
symElem.src = e + sym;
symContainer.appendChild(symElem);
});
</script>
I need a little help with a Javascript function I am creating. In essence, I need to loop through a set of DIVs with class .DetailRow and find a child DIV's content (inner text). If this text is matched to a variable, then I need to replace this inner text with an IMG HTML statement.
BTW I am kinda new at this (4 months old!) so apologies if the issue is simple, but I have tried a few combos and I am stuck.
Here's the HTML:
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">
<div class="Label">Availability:</div>
<div class="Value">in stock + Free Shipping</div>
</div>
Example, if I find "in stock" in the LABEL inner text, I want to replace it with the value of the variable "instock" which is an IMG HTML statement. See my code attempt below.
<script type="text/javascript">
$(window).load(function(){
var instock = '<img src="https://linktoimgfolder/instock.gif" title="Product available, usually ships 24hrs to 48hrs after order receipt" style="margin-top:-3px;">';
var lowstock = '<img src="https://linktoimgfolder/lowstock.gif" title="Product stcok low, order today so you do not miss out">';
var nostock = '<img src="https://linktoimgfolder/outstock.gif" title="Product out of stock, could ship 1 to 2 weeks after order receipt">';
$('div.DetailRow')each(function(){
if (indexOf($(this).childNodes[1].innerHTML, "in stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = instock;
} else if (indexOf($(this).childNodes[1].innerHTML, "low stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = lowstock;
} else {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = nostock;
};
});
});
</script>
By the way,m I cannot match text exactly as the text beyond the "+" will change from time to time, thus I am trying indexOf.
Many thanks in advance for your assistance!
M
Using the :contains selector
var stock = {'in stock': instock, 'low stock': lowstock, 'no stock': nostock};
Object.keys(stock).forEach(function(key) {
$('div.DetailRow div:contains(' + key + ')').html(stock[key]);
});
jsFiddle Demo
A pure jQuery solution:
$.each(stock, function(key, value) {
$('div.DetailRow div:contains(' + key + ')').html(value);
});
You have typo in this line $('div.DetailRow')each(function(){ and then you can use jQuery .text() and .html() to check value and update.
Try:
$('div.DetailRow').find("div").each(function(){
if($(this).text().indexOf("in stock")!=-1){
$(this).text("");
$(this).html(instock);
}else if($(this).text().indexOf("low stock")!=-1){
$(this).text("");
$(this).html(lowstock);
}else{
$(this).text("");
$(this).html(nostock);
}
});
DEMO FIDDLE
NOTE: Updated code to find div inside div.DetailsRow. Change it according to your requirement.
I have here this code:
var photo = place.photos[0].getUrl({ 'maxWidth': 50, 'maxHeight': 50 });
var sideClick = jQuery("<a class=side_click href='#'></a>");
$(sideClick).html(place.name+place.rating);
$("#side_bar").append("<div class='elemenat'><div class='draggable'><img style='margin-left:3px; margin-top:5px;' src="+ photo +" width='46' height='42' /></div><div class='elementname'>").append(sideClick).append("</div></div>");
$(sideClick).on("click", function() {
markers[i].modalWindow_.getDetails(markers[i].place_);
});
}
and this code render:
<div id="side_bar">
<div class="elemenat">
<div class="draggable ui-draggable">
<img style="margin-left:3px; margin-top:5px;" src="https://lh6.googleusercontent.com/-T0_fJX5zza0/UdSnOaucZvI/AAAAAAAAAFc/gQhK3IbHJfY/w50-h50-s0/Small%2BLogo.png" width="46" height="42"></div>
<div class="elementname"></div></div>
<a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a>
How I must change js code to render html where <a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a> will be into <div class="elementname"></div> so
must be rendered like this:
<div class="elementname">
<a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a>
</div>
Don't create elements by raw HTML text. Instead, use jQuery's DOM manipulation capabilities. It makes things much simpler to understand, maintain and less error-prone.
So instead of something like:
var sideClick = jQuery("<a class=side_click href='#'></a>");
$(sideClick).html(place.name + place.rating);
It is better to do:
var sideClick = $("<a>").addClass('side_click').attr('href', '#')
.text(place.name + place.rating);
Besides being easier to structure and spot errors, you also get the added benefit of escaping the place.name + place.rating string.
Check the updated code using this approach (and with the end result you expected):
var photo = place.photos[0].getUrl({
'maxWidth': 50,
'maxHeight': 50
});
var elemenatDiv = $('<div>').addClass('elemenat');
var draggableDiv = $('<div>').addClass('draggable');
var logo = $('<img>').css({'margin-left': '3px', 'margin-top': '5px'})
.attr('src', photo).attr('width', 46).attr('height', 42)
var sideClick = $("<a>").addClass('side_click').attr('href', '#')
.text(place.name + place.rating);
var elementnameDiv = $('<div>').addClass('elementname');
elemenatDiv.append(draggableDiv.append(logo));
elemenatDiv.append(elementnameDiv.append(sideClick));
$("#side_bar").append(elemenatDiv);
$(sideClick).on("click", function () {
markers[i].modalWindow_.getDetails(markers[i].place_);
});
See demo fiddle here.
Append sideclick to the elementname div, not to the side_bar div
var element = $("<div class='elemenat'><div class='draggable'><img style='margin-left:3px; margin-top:5px;' src="+ photo +" width='46' height='42' /></div>");
var elementName = $(<div class='elementname'>);
element.append(elementName);
elementName.append(sideclick);
$("#side_bar").append(element);
Take a look at http://api.jquery.com/category/manipulation/.
You have a couple of different options. You could just change the order in which you append things, use the InsertAfter or InsertBefore methods, or my personal recommendation, putting everything onto the DOM and then using the wrap() function to wrap the side_click link with the div.
Something like
\\append everything
$('.side_click').wrap('<div class="elementname" />');
Hi i would like to create an array from the title and src of an image set. Then append it to a list, then clear the array (the images in the set changes) then clear the array and the list. repeat it again and again as the images change in the set.
Here is the HTML:
<div id="imageholder">
<img src="images/a001.png" title="orange"/>
<img src="images/a002.png" title="red apple"/>
<img src="images/a003.png" title="green apple"/>
<img src="images/a004.png" title="red apple"/>
</div>
<ul id="list"></ul>
and here is the code:
title_array = [];
src_array = [];
function sumarychange() {
$("#imageholder img").each(function() {
// pushing each values into arrays
title_array.push($(this).attr("title"));
src_array.push($(this).attr("src"));
// i think this part will append the content in the arrays
var list = $('#list');
var existing_item = $('#list_'+ title);
// removing items with the same titles
if (existing_item.length < 1){
var new_item = $('<li />');
new_item.attr('id', 'list_'+ title);
new_item.html('<div>' + title + '</div><img src="' + src + '" />');
list.append(new_item);
}
});
// i think this will set the arrays back to empty
title_array.length = 0;
src_array.length = 0;
}
this is just a sample. In actual the image has more tags. i have no clue how to empty out the list when this function is called again. im just learning coding now and i have no idea how to correct this to make it work.
This looks to me like an XY problem.
Judging from your example code above as well as your previous question, I'm guessing what you're trying to do is update a list of entries based on the attributes of an existing set of elements, but with items with duplicate titles only displayed once.
Assuming I got that right, here's one way to do it: (demo: http://jsfiddle.net/SxZhG/2/)
var $imgs = $("#imageholder"), $list = $("#list");
function summary_change() {
// store data in tmp obj with title as key so we can easily ignore dups
var store = {};
$imgs.find("img").each(function() {
if (store.hasOwnProperty(this.title)) return; // ignore dup title
store[this.title] = this.getAttribute("src");
});
$list.empty(); // empty the list
for (var title in store) { // add new list items
$("<li>")
.append($("<div>", {"text":title}))
.append($("<img>", {"src":store[title]}))
.appendTo($list);
}
}
Note that if more than one image has the same title, only the src of the first one is used in the summary results. If you wish to use the src of the last item found, simple remove the line if (store.hasOwnProperty(this.title)) return;.
I have a next string like:
<img src="../uplolad/commission/ranks/avatar.jpg' . $row[$c_name] .'" width="50" height="50"/>
How can i get a image file name in javascript? I know only PHP regexes. Extention of a file can be different.
The result must be: avatar.jpg
Regex is not ideal for this. JavaScript can traverse the HTML as distinct objects more readily than as a long string. If you can identify the picture by anything, say by adding an ID to it, or an ID to a parent with that as the only image, you'll be able to access the image from script:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
var src = myImage.src; // will contain the full path
if(src.indexOf('/') >= 0) {
src = src.substring(src.lastIndexOf('/')+1);
}
alert(src);
And if you want to edit, you can do that just as well
myImage.src = src.replace('.jpg', '.gif');
Fetch it following coding which can help what you want to get.
<script type="text/javascript">
function getImageName(imagePath) {
var objImage = new RegExp(/([^\/\\]+)$/);
var getImgName = objImage.exec(imagePath);
if (getImgName == null) {
return null;
}
else {
return getImgName[0];
}
}
</script>
<script>
var mystring = getImageName("http://www.mypapge.mm/myimage.png")
alert(mystring)
</script>
Here's a shorter variation of David Hedlund's answer that does use regex:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));