Change image depending on page title - javascript

What I'm trying to do is depending on the page title, an image in the body would change. For example, if the page title is "We Love Apples," the image in the body would be an apple. If the title contains another fruit, it would show that other fruit. If the page title doesn't contain any word that the script is looking for, then there would be a default image in the body.
I did find this script from http://www.codingforums.com/archive/index.php/t-218600.html but I can't seem to make it work.
Anyone has any tips or pointers? Appreciate the help!
<!doctype html>
<html>
<title>2image</title>
<head>
</head>
<body>
<div><img src="" alt="anImageDesc" name="myimage" width="50px" height="50px" id="someImage" />
</div>
<script type="text/javascript">
var imgs = [
"http://www.domain.com/images/image_255 Company_Name.jpg",
"http://www.domain.com/images/image_256 Company_Name.jpg",
"http://www.domain.com/images/image_257 Company_Name.jpg" //no comma after last image
];
var el = document.getElementById("someImage");
var title = document.title;
for (var i=0;i<imgs.length;i++){
if (imgs[i].indexOf(title) != -1) {
el.src = imgs[i];
break;
} else {el.src = "image_256.gif"} //a default image incase nothing is found
}
</script>
</body>
</html>

See this: DEMO
I would suggest having a key/value map of tokens to look for in the title, and associating the appropriate image with that token:
var images = {
'very large apple' : 'http://www.domain.com/images/very_large_apple_image_here.jpg',
'large apple' : 'http://www.domain.com/images/large_apple_image_here.jpg',
'apple' : 'http://www.domain.com/images/apple_image_here.jpg',
'orange' : 'http://www.domain.com/images/orange_image_here.jpg'
};
var defaultImage = images['apple']; //Set your default here.
var imageElement = document.getElementById("someImage");
var title = document.title.toLowerCase();
var source = null;
for (var t in images) {
if (title.indexOf(t.toLowerCase()) != -1) {
source = images[t]; //Found a match.
break;
}
}
if (!source) source = defaultImage;
imageElement.src = source;

Use document.title to get the window title, and set your image based on that. I used toUpperCase() to make sure you find the text you are looking for regardless of case. search() will return -1 if the text is not found.
if(window.title.toUpperCase().search('APPLE') > 0)
{
//change image to apple
}
else if(document.title.toUpperCase().search('ORANGE') > 0)
{
//change image to orange
}
else
{
//use the default image
}

Define what fruits to look for, then check the title to see if it contains any of the fruits, then find the appropriate image :
var fruits = [
'apple',
'orange',
'grape'
]
var imgs = [
"http://www.domain.com/images/image_255_grape.jpg",
"http://www.domain.com/images/image_256_orange.jpg",
"http://www.domain.com/images/image_257_apple.jpg"
];
var fruit = 'apple', // default
img = '';
// check the title for fruit
for (var i=0; i<fruits.length; i++) {}
if ( document.title.indexOf(fruits[i]) != -1 ) fruit = fruits[i];
}
//find matching image
for (var i=0; i<imgs.length; i++) {}
if ( imgs.indexOf(fruit) != -1 ) img = imgs[i];
}
var el = document.getElementById("someImage");
el.src = img;

Create a lookup:
var myList = {
images: [{
id: "grape",
name: "somelocation/file.png"
}, {
id: "crabapple",
name: "c:/images/brightblue.png"
}, {
id: "lime",
name: "grassgreen.png"
}, {
id: "bannana",
name: "dollarbill.png"
}]
};
var lookup = {};
// create refernece to list above and use it everywhere
lookup.list = myList;
for (var i = 0, len = lookup.list.images.length; i < len; i++) {
lookup[lookup.list.images[i].id] = lookup.list.images[i];
}
alert(lookup['lime'].name);
and for the title:
lookup[document.title].name;

Related

I need to create a gallery of images from an Array with JSON object

I have a task for a homework i was give where i need to create a simple gallery which displays 4 images.
i need to put all images into Array where each photo will be in JSON object and load the images from the array . This is where i am now:
<body>
<div class="images">
</div>
(function (){
let array_img = [
{
filename:"20140222_131314",
title:"img1",
},
{
filename:"20140712_203709",
title:"img2",
},
{
filename:"20190318_182928",
title:"img3"
},
{
filename:"20190422_181219",
title:"img4"
}
]
for (var i = 0 ; i<array_img.length ; i++){
arr_img = array_img[i]
var container = $(".images");
$container.append("<img/>").attr("src=/Photos/20140222_131314.jpg")
}
}());
Or should i create an additional variable img= array_img[i] and to create a text node from it and after that to append . But how to append and set the src path to all images. Maybe i need to create and empty "src" to the object sctructure?
But i am missing something . Can someone help me?
This should run. Make sure that you have a $ before your variables.
(function() {
let array_img = [{
filename: "20140222_131314",
title: "img1",
},
{
filename: "20140712_203709",
title: "img2",
},
{
filename: "20190318_182928",
title: "img3"
},
{
filename: "20190422_181219",
title: "img4"
}
]
for (var i = 0; i < array_img.length; i++) {
$arr_img = array_img[i]
var $container = $(".images");
$container.append("<img src=/Photos/"+$arr_img[0]+".jpg/>");
}
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="images">
</div>
I made it like that and now it works . I don't know if this is the best way to do it but...
(function (){
let array_img = [
{
filename:"20140222_131314.jpg",
title:"img1",
},
{
filename:"20140712_203709.jpg",
title:"img2",
},
{
filename:"20190318_182928.jpg",
title:"img3"
},
{
filename:"20190422_181219.jpg",
title:"img4"
}
]
for (var i = 0 ; i<array_img.length ; i++){
var arr_img = array_img = [i]
var $container = $(".images");
$container.append(arr_img[i+1],"<img src=photos/20140222_131314.jpg>")
$container.append(arr_img[i+1],"<img src=photos/20140712_203709.jpg>")
$container.append(arr_img[i+1],"<img src=photos/20190318_182928.jpg>")
$container.append(arr_img[i+1],"<img src=photos/20190422_181219.jpg>")
}
}());

How to display images in a table dynamically?

I am making a table whose data is dynamically changed with the following script. I also want to display the respective images of the groups beside the group names. When the group names will change, the image will also change.
The table works absolutely fine.
The image files are there in my ide, so the path mentioned is correct. However the images are not displayed.
<script>
//$, jQuery
var lookupTable = {
Palm: "PM",
Cedar: "CED",
Oak: "OA",
Chinar: "CHI"
};
var setGroup = function(groupName) {
var t = jQuery('<div></div>').addClass('group');
var tn = jQuery('<div></div>').addClass('group-name').appendTo(t);
jQuery('<img>').attr('src','/examples/media/images/'+ groupName.toLowerCase() + '.png').appendTo(tn);
jQuery('<span></span>').text(groupName).appendTo(tn);
return t;
};
$.getJSON('https://service_program', function(data){
var taf = $('#item1').empty();
var tar = $('#item2').empty();
var tat = $('#item3').empty();
var tao = $('#item4').empty();
jQuery.each(data, function(idx, game){
if (game['Category'] === 1){
var tr = $('<tr></tr>').appendTo(taf);
} else if (game['Category'] === 2) {
var tr = $('<tr></tr>').appendTo(tar);
} else if (game['Category'] === 3){
var tr = $('<tr></tr>').appendTo(tat);
} else if (game['Category'] === 4){
var tr = $('<tr></tr>').appendTo(tao);
}
$('<td></td>').text(game['group 1']).appendTo(tr);
$('<td></td>').text(game['group 2']).appendTo(tr);
$('<td></td>').text(game['itemName 1']).appendTo(tr);
$('<td></td>').text(game['itemName2']).appendTo(tr);
});
});
</script>
Where am I going wrong?
use this:
$('<td></td>').$('<img>').attr('src','/examples/media/image/'+ groupName.toLowerCase() + '.png').appendTo(tr);

Zingchart last element keeps changing color and not matching with legend

My zingchart's last element's color does not match with legend, and keeps on changing unlike the others. Any Ideas? Everything else works good. Though I'm parsing this data through MySQL database, this is how the JavaScript looks like.
My code:
<script>
var myData = ["12","15","7","20","2","22","10","7","7","10","8","15","9"];
var myData = myData.map(parseFloat);
var myLabels = ["General Verbal Insults","General Beatings\/Pushing","Terrorizing\/Threatening Remarks","False Gossip Inflation (Rumors)","Discrimination","Rough Fighting","Sexual Utterance\/Assaults","General Exclusion","Theft","Racist Utterance\/Assaults","Personal Property Damage","Internet Related (Cyber)","Other\/Unspecified"];
window.onload=function(){
var colorCharacters = "ACDEF0123456789";
var globalStylesArray = [];
var myConfig = {
type: "bar",
legend:{},
title: {
"text":"Showing Results For: Canada",
"color":"green"
},
subtitle: {
"text":"Total Bullying Incidents In Country: 144",
"color":"blue"
},
series : [{"values":[ myData[0] ],"text":"General Verbal Insults",},{"values":[ myData[1] ],"text":"General Beatings/Pushing",},{"values":[ myData[2] ],"text":"Terrorizing/Threatening Remarks",},{"values":[ myData[3] ],"text":"False Gossip Inflation (Rumors)",},{"values":[ myData[4] ],"text":"Discrimination",},{"values":[ myData[5] ],"text":"Rough Fighting",},{"values":[ myData[6] ],"text":"Sexual Utterance/Assaults",},{"values":[ myData[7] ],"text":"General Exclusion",},{"values":[ myData[8] ],"text":"Theft",},{"values":[ myData[9] ],"text":"Racist Utterance/Assaults",},{"values":[ myData[10] ],"text":"Personal Property Damage",},{"values":[ myData[11] ],"text":"Internet Related (Cyber)",},{"values":[ myData[12] ],"text":"Other/Unspecified",}]
};
zingchart.render({
id : 'myChart',
data : myConfig,
width:"100%",
height:500,
});
zingchart.gload = function(p) {
console.log(p);
var graphId = p.id;
var graphData = {};
graphData = zingchart.exec(graphId, 'getdata');
graphData = graphData.graphset[0] ? graphData.graphset[0] : graphData;
console.log(graphData);
createColors(graphData.series[0].values.length);
zingchart.exec(graphId, 'modifyplot', {
data: {
styles: globalStylesArray
}
});
}
function createColors(seriesLength) {
console.log('-------createColor seriesLength: ', seriesLength);
globalStylesArray = [];
for (var i = 0; i < seriesLength; i++) {
var colorString = '#';
for (var j = 0; j < 6; j++) {
colorString += colorCharacters.charAt(Math.floor(Math.random() * (colorCharacters.length - 4)));
}
globalStylesArray.push(colorString);
}
console.log('-----globalStylesArray-------', globalStylesArray);
}
};
</script>
Referring to the comment on the OP:
I just want all color to be different, since i dont know how many elements are in MyData - its generated through PHP & MYSQL
If you just want all of the colors to be different, remove the zingchart.gload function and the createColors function. ZingChart will create different colors for each series dynamically.
If you do want to specify each of those colors ahead of time since you do not know how many series your data will produce, you will need to apply a theme to your chart configuration: http://www.zingchart.com/docs/design-and-styling/javascript-chart-themes/

Trouble styling a DIV with two background images using Javascript Objects

I can only get the CSS styled image to load. The browser does not display imgB. The source code also only shows imgA. I just want to call the backgroundImage value of the Object at the time of the specific loop
My HTML.
<div onclick="displayCards()">Display Cards</div>
My Javascript Objects contain properties for these DIV elements. The different cards each have a unique image imgB. I created an array for the Objects so I can loop through them with a for loop.
var card_troop = { title : "troop" , type : "Unit" , image : "url(troop.png)" } ;
var card_base = { title : "base" , type : "Structure" , image : "url(base.png)" } ;
var card_wood = { title : "wood" , type : "Resource" , image : "url(wood.png)" } ;
var list = [
card_troop ,
card_base ,
card_wood
] ;
The DIV elements are created by my displayCards() function, that are appended to the body of my HTML document.
function displayCards()
{
card = document.createElement("div") ;
var card_id = document.createAttribute("id") ;
card_id.value = list[x].title ;
card.setAttributeNode(card_id) ;
var card_class = document.createAttribute("class") ;
switch (list[x].type) // Card Theme Comparison
{
case "Unit" :
card_class.value = "unit" ;
break ;
case "Structure" :
card_class.value = "structure" ;
break ;
case "Resource" :
card_class.value = "resource" ;
break ;
}
card.setAttributeNode(card_class) ;
var imgA = card.style.backgroundImage ;
var imgB = list[x].image ;
card.style.backgroundImage = imgA + " , " + imgB ;
}
Using the switch Comparison, switch (list[x].type), defined by the Object Property type:, each DIV will have one of three CSS backgroundImage values.
div.unit { background-image:url( theme_unit.png ) ; }
div.structure { background-image:url( theme_structure.png ) ; }
div.resource { background-image:url( theme_resource.png) ; }
Another function builder() calls displayCards() and appends the Object card.
function builder()
{
for ( x = 0 ; x < 9 ; x++ )
{
displayCards() ;
document.body.appendChild(card) ;
}
}
I believe my problem lies here. Since the DIV is still not appended.
To note:imgA is a higher index than imgB and has transparency to allow imgB to be seen.
var imgA = card.style.backgroundImage ;
var imgB = list[x].image ;
card.style.backgroundImage = imgA + " , " + imgB ;
I am a minimalist coder and this is the shortest I could come up with. I do not want to have to repeat URL's more than once. My list of Objects is going to get much longer than three.
NO JQUERY
var card_troop = { title : "troop" , type : "Unit" , image : "url(troop.png)" } ;
var card_base = { title : "base" , type : "Structure" , image : "url(base.png)" } ;
var card_wood = { title : "wood" , type : "Resource" , image : "url(wood.png)" } ;
var list = [
card_troop,
card_base,
card_wood
];
function buildCard(card) {
var elem = document.createElement('div'),
elemCloned,
computedBackgroundUrl,
backgroundUrl;
elem.id = card.title;
elem.className = card.type.toLowerCase();
// Clone element and temporary append to body
elemCloned = elem.cloneNode();
elemCloned.style.display = 'none';
document.body.appendChild(elemCloned);
computedBackgroundUrl = window.getComputedStyle(elemCloned)['background-image'];
if (computedBackgroundUrl) {
var match = computedBackgroundUrl.match(/^url\((.*)\)/);
if (match) {
backgroundUrl = match[1];
}
}
// remove element after retrieved background-image value
elemCloned.parentNode.removeChild(elemCloned);
elemCloned = null;
elem.style.backgroundImage = (backgroundUrl ? 'url(' + backgroundUrl + '), ' : '') + card.image;
computedBackgroundUrl = null;
backgroundUrl = null;
return elem;
}
function displayCards() {
var body = document.body;
for (var i = 0, len = list.length; i < len; i++) {
body.appendChild( buildCard(list[i]) );
}
}
Never got efficient in js but your js solution should be the js parallel.
add/remove the class on the div and swap background images according to class in css. I'm assuming this would require less js as a bonus.
hope this helps.
You should work through this approach. Replace "backgroundimage" and "foregroundimage" with the appropriated URLs (of course).
Afterwards you can call the method showCard with a switch. showCard(true) shows the card's front. showCard(false) shows the card's back.
var card = function(title, type, image) {
this.title = title;
this.type = type;
this.image = image;
this.background = "url('backgroundimage')";
};
card.prototype.showCard = function(turn) {
if (turn) {
var ele = document.createElement("div");
ele.appendChild(document.createTextNode(this.title));
ele.appendChild(document.createTextNode(this.type));
ele.style.backgroundImage = this.image;
document.body.appendChild(ele);
} else {
var ele = document.createElement("div");
ele.style.backgroundImage = this.background;
document.body.appendChild(ele);
}
};
function displayCards() {
var card_troop = new card("TroopTitle", "TroopType", "url('foregroundimage')");
card_troop.showCard(true);
var card_troop_2 = new card("Troop2Title", "TroopType", "url('foregroundimage2')");
card_troop_2.showCard(false);
};
div {
min-width: 50px;
height: 120px;
border: solid;
float: left;
}
<input type="button" onclick="displayCards()" value="Display Cards" />

Values are not being saved to the array

I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});

Categories