Javascript add individual Image - javascript

keywords = [
"http://www.website-for-hair.com/",
"http://www.website-for-shoes.com/"
]
var keyword = keywords[Math.floor(Math.random()*keywords.length)]
document.write('<img src="http://i.imgur.com/test.jpg" title="Test Title" />');
The above code works perfectly however it spins only the domain. I am now required to add individual images for each website and then output domain+image using +keyword+ together?

Here's one way that's similar to how you did it before:
var websites = [
{ url: "http://site1.com", image: "http://site1.com/logo.png" },
{ url: "http://site2.com", image: "http://site2.com/logo.jpg" }
];
var website = websites[Math.floor(Math.random * websites.length)];
document.write(
'<a href="' + website.url + '">' +
'<img src="' + website.image + '" title="foo" />' +
'</a>'
);

You could use a list of lists.
Each list contained in that list would store the URL (position 0, keywords[random_index][0]) and its corresponding image source (position 1, keywords[random_index][1]).
You should also store the random index that you generate in a variable to ensure you always access the same sublist.
For example:
keywords = [
["http://www.website-for-hair.com/", "imgA"],
["http://www.website-for-shoes.com/", "imgB"]
]
var random_index = Math.floor(Math.random()*keywords.length);
var keyword = keywords[random_index][0];
var image = keywords[random_index][1];
document.write('<a href='+keyword+'><img src='+image+' title="Test Title" /></a>');

Related

How can I load data from a service that returns JSON and create content using jQuery?

I am a beginner in JS .. so I am reaching out to you, hoping someone could enlighten me! :)
I have been given a JSON link listing a lot of infos and I must create an html using at least 2 pieces of info from this JSON link.
I have already imported my stylesheets (+script) in the html and I coded this in my script.js :
$.getJSON('myjsonlink', function(json) {
console.log(json);
});
If one of you guys have a moment to give me hand, it would be awesome! Thank you so much in advance.
Athena.
There are few issues with the way you are reading data and rendering it:
There is no naruto property on response, it is results instead.
img is not a valid property, it should be image_url instead.
Let's fix it:
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://api.jikan.moe/v3/search/anime?q=naruto', function(data) {
var naruto = data.results;
for (var i = 0; i < naruto.length; i++) {
var anime = naruto[i];
var html = '<div class="card">' + '<img src="' + anime.image_url + '">' + '<div class="cardcontainer">' + '<p>' + anime.title + '</p>' + '<p>' + anime.synopsis + '</p>' + '</div>' + '</div>';
showData.append(html);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="get-data">Load Data</button>
<div id="show-data"></div>

Javascript Image/Text Object

I was trying to give an object an Image but I doesn`t give it back . What did I wrong ? ^^
var bank = {
money:"$",
currency:"Dollar",
sum:50,
src: "Logo.png"
};
document.getElementById("test").innerHTML= " Your amount is" + bank.sum + " "+ bank.money + "("+ bank.currency+")" + bank.src;
You are not using an image anywhere as far as I can tell. You can't just give an "image" to javascript. You can store the URL to an image in javascript, and then you can assign this to an HTML <img>tag.
In html the tag would look like <img id="testimage" src="Logo.png/>. Then you could use javascript to change the image source. You could do it like
var image = document.getElemenyById("testimage");
image.src = bank.src;
Or, if you want to add an image to the body completely in Javascript, you could do that as well.
as you have commented on your answer, I guess this is the way you actually want to do it
var img = document.createElement("img"); // creates <img>
img.src = bank.src; // sets the source to the source of the 'bank'
document.getElementsByTagName("body")[0].appendChild(img); // adds it to the body
You could of course add it to your (div?) which you are using the your question.
document.getElementById("test").appendChild(img);
Try adding the image in an <img> element like this:
document.getElementById("test").innerHTML= " Your amount is" + bank.sum + " "+ bank.money + "("+ bank.currency+")" + " `<img src= '"+bank.src+"' />` ";
Is it possible to box an object like this ?
var screenX1 = {
image:"image001.png",
links: {
link {
area:[45, 143, 106, 158];
reference to screenx2
}
link {
area:[45, 143, 106, 158];
reference to screenx3
}
},
};
var screenx2 = {
......
Add img tag for show image like below.
document.getElementById("test").innerHTML="Your amount is " + bank.sum + " "+ bank.money + " ("+ bank.currency+")" + "<img src='"+bank.src+"' />";

How to add alternating classes to dynamic feed of thumbnail images?

I am bringing a feed of a youtube user's video channel onto a page via two plugins called jYoutube and jGFeed.
jGFeed: http://archive.plugins.jquery.com/project/jgfeed
jYoutube: http://archive.plugins.jquery.com/project/jyoutube
I am getting stuck on why this isn't working... I thought it would be as easy as a simple if/else statement, but it is not working.
jQuery(document).ready(function($) {
$.jGFeed('http://gdata.youtube.com/feeds/base/users/POTATOwillEATyou/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile',
function(feeds){
// Check for errors
if(!feeds){
// there was an error
return false;
}
var html = '';
// do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
//My attempt at alternating classes:
if((i%2) == 0)
{
console.log('hello')
$(".thethumb").addClass("even");
}
else
{
console.log('NOPE')
$(".thethumb").addClass("odd");
}
//End of my attempt
html += '<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>';
}
$('#you_tube_feed').html(html);
}, 25);
});
Your issue is that you are are changing the class of ALL .thethumb, and they don't exist at the time you're running that code (they're inside your html string)
for(var i=0; i<feeds.entries.length; i++)
{
var entry = feeds.entries[i];
var $new = $('<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>');
if((i%2) == 0)
{
$new.addClass("even");
}
else
{
$new.addClass("odd");
}
$('#you_tube_feed').append($new);
}
Since you are using JQuery, it's even more simple . . . add all of the thumbnails first and then go back use the :even and :odd selectors to add the classes all at once:
$('.thethumb:even').addClass('odd');
$('.thethumb:odd').addClass('even');
You'll noticed that the classes are switched in comparison to the selectors . . . that is because the JQuery selector is 0-based, so items "0", "2", "4", etc. are actually the 1st, 2rd, 5th, etc. items in the selection.

Add class to image onload - determine if landscape

I am trying to add a class to an image after determining if it is landscape or portrait. The problem I am having is that the class is being added to the img tag like this img.landscape which is obviously not registering properly. How can I properly achieve this: <img class="landscape" ?
$(data.images).each(function(j, imageURL){
var thumbnail = new Image();
thumbnail.src = imageURL;
thumbnail.onload = function() {
$('.images').append('<div class="image_mask"><img src="' + imageURL + '"/></div>');
if (thumbnail.width > thumbnail.height){
$(this).addClass('landscape');
}
};
});
My previous solution was to include an if/else statement with the class added in the appended string, but I am wondering if there is a cleaner way of approaching this. Thanks!
EDIT--
http://jsfiddle.net/curly33/XeHzK/1/
I'm assuming you want to add a class to the <img> tag you're dynamically creating a few lines before? If so, you can do so like this:
$('.image_mask img').addClass('landscape');
Since it's in a loop and you'll have multiple div.image_mask, use the array index j as a class qualifier:
$(data.images).each(function(j, imageURL){
...
thumbnail.onload = function() {
$('.images').append('<div class="image_mask image_mask' + j + '"><img src="' + imageURL + '"/></div>');
// ^^^^^^
if (thumbnail.width > thumbnail.height){
$('.image_mask' + j + ' img').addClass('landscape');
// ^^^^^^
}
};
});
UPDATE
Even though this was accepted, it feels clumsy to me to add class names like I originally suggested. A cleaner approach would be to use the j array index variable in combination with jQuery's eq function to locate the relevant image mask:
$('.images .image_mask').eq(j).addClass('landscape');
..then do away with the whole adding of classes approach.
Just put it in your string building
$(data.images).each(function(j, imageURL){
var thumbnail = new Image();
thumbnail.src = imageURL;
thumbnail.onload = function() {
var orientationClass = thumbnail.width > thumbnail.height ? "landscape" : "portrait";
$('.images')
.append(
'<div class="image_mask"><a href="' +
imageURL +
'"><img class="' +
orientationClass +
'" src="' +
imageURL +
'"/></a></div>'
);
};
});
Edit: More options
If you want to make it more verbose, but cleaner, you could build out the elements one by one:
var $img = $('<img />', {
class: thumbnail.width > thumbnail.height ? "landscape" : "portrait",
src: imageUrl
});
var $a = $('<a />', {
href: imageUrl,
}).append($img);
var $div = $('<div />', {
class: "image_mask"
}).append($a);
$('.images').append($div);
Or if you want to use the more efficient string building, but what it to be more readable/performant, you could do an array with a join:
var contents = [
'<div class="image_mask"><a href="',
imageURL ,
'"><img class="',
orientationClass,
'" src="',
imageURL,
'"/></a></div>'];
$('.images').append(contents.join(''));

Not all Ajax content loading on one domain

I have the domain http://whatthecatdragged.in/ forwarded (cloaked) to http://moppy.co.uk/wtcdi/
The root page (index.html) uses Ajax to load the content. At the original host (moppy.co.uk/wtcdi) the page and all content loads. However, at the domain forwarded domain (whatthecatdragged.in), some of the content does not load. Has it something to do with the way .each is used to fire off Ajax calls, as mentioned by AnthonyWJones?
I've attempted to debug this, but peculiarly turning on the Firebug console in Firefox 3.5 actually seems to make all the content load.
// Content building code:
$(function() {
// Set a few variables (no need for secrecy with Flickr API key).
var apiKey = 'myapikey';
// var tags = '';
var tagsArr = new Array();
// Get the photos of flickr user WhatTheCatDraggedIn.
// This Ajax call always seems to complete.
$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' +
apiKey +
'&user_id=46206266#N05&extras=date_taken,tags&format=json&jsoncallback=?',
function(data) {
// Set some variables to ensure alldata is fecthed from second API
// call (below) before building majority of content.
var totalExpected = data.photos.total;
var totalFetched = 0;
var photohtml = '';
// For each photo, do the following:
$.each(data.photos.photo, function(i, item) {
// Set size of photo thumbnail to display.
var size = 's';
var append = '';
if (i == 0) {
// Display most recent thumbnail larger, and add a line
// break for small pics beneath it.
size = 'm';
append = '<br />'
}
//Only display thmbnails of 4 most recent catches (1 large, 3 small).
if (i <= 3) {
var photoSrc =
'http://farm' + item.farm + '.static.flickr.com/' +
item.server + '/' + item.id + '_' + item.secret + '_' +
size + '.jpg'
//Each thumbnail links to that photo's Flickr page.
var flickrPage =
'http://flickr.com/photos/' + item.owner +
'/' + item.id + '/';
// Each thumbnail has a big tooltip, with tags formatted appropriately.
var formattedTags = item.tags.replace(/\s/g, "<br />");
formattedTags = formattedTags.replace(/cat/, "cat: ");
formattedTags = formattedTags.replace(/loc/, "location: ");
formattedTags = formattedTags.replace(/victim/, "victim: ");
formattedTags = formattedTags.replace(/status/, "status: ");
formattedTags = formattedTags.replace(/floor/, " floor");
formattedTags = formattedTags.replace(/toy/, " toy");
//Append the built html to one varable for adding to page shortly
photohtml +=
'<a class="flickr-page-link" href="' +
flickrPage + '"><img src = "' +
photoSrc + '" title="' + formattedTags + '"/>' +
append + '</a>';
}
var photoID = item.id;
// Get the detailed photo information (including tags) for the photo.
// This is the call that perhaps fails or at least content
// generated after this call does not load.
$.getJSON(
'http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' +
apiKey + '&photo_id=' + photoID +
'&format=json&jsoncallback=?',
function(data) {
if (data.photo.tags.tag != '') {
$.each(data.photo.tags.tag, function(j, item) {
// Place all tags in an aray for easier handling.
tagsArr.push(item.raw);
});
// Incrememt number of photos fetched.
totalFetched += 1;
// Have we got them all?
if (totalFetched == totalExpected)
fetchComplete();
}
});
// Builds a shedload more content once all JSON calls are completed.
function fetchComplete() {
// ### BUILD VICTIM list ###
// format a regex to match tags beginnign : "victim: "
var vicRe = /^v[a-z]+:\s([a-z\s]+)/
// Match the regex to the tags and count number of matches per tag.
var vicCounts = tagsArr.countVals(vicRe);
var victimsHtml = "";
// For each victim.
for (var i in vicCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
console.debug(strippedTag);
// Add a line of html with the type of victim and the number of victims of that type
victimsHtml +=
"<a href='http://flickr.com/photos/46206266#N05/tags/victim" +
strippedTag + "/'>" + [i] +
" (" + vicCounts[i] + ") </a><br />";
};
// Replace existing HTML with new version.
$('#types-dragged').html(victimsHtml);
// ### BUILD STATUS PIE CHART ###
// Build a theme for chart colours.
var wtcdicharttheme = {
colors: ['#C66800', '#D3C70B', '#DD3D0B', '#D30729',
'#DDA70B'
],
marker_color: '#000000',
font_color: '#000000',
background_colors: ['#ffffff', '#ffffff']
};
// Create a new chart object, include css id of canvas
// where chart will be drawn.
var g = new Bluff.Pie('status', '275x250');
// Set a theme and stuff.
g.set_theme(wtcdicharttheme);
// No title, as this exists via the raw page HTML.
g.title = '';
g.legend_font_size = "50px";
g.marker_font_size = "20px";
// Build a regex string to match tags beginning "status: ".
var statRe = /^s[a-z]+:\s([a-z\s]+)/
// Match regex to tags and return an object with tag
// names and number of occurences.
var statCounts = tagsArr.countVals(statRe);
// For each status.
for (var i in statCounts) {
// Add data to the chart
g.data([i], [statCounts[i]]);
};
// Draw the chart.
g.draw();
// ### BUILD LOCATION LIST ###
// Build a regex that matches tags beginning "loc: "
var locRe = /^l[a-z]+:\s([a-z\s]+)/
// Match regex to tags and return an object with
// tag names and number of occurences.
var locCounts = tagsArr.countVals(locRe);
var locatHtml = "";
// For each location.
for (var i in locCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
// Add a line of html with the location and the
//number of times victims found in that location.
locatHtml +=
"<a href='http://flickr.com/photos/46206266#N05/tags/loc" +
strippedTag + "/'>" + [i] + " (" +
locCounts[i] + ") <br />";
};
// Replace existing html with newly built information.
$('#locations').html(locatHtml);
// ### BUILD CAT LIST ###
// Build a regex that maches tags beginning "cat: ".
var catRe = /^c[a-z]+:\s([a-z_\s]+)/
//Match regex to find number of catches each cat has made
var catCounts = tagsArr.countVals(catRe);
// For each cat.
for (var i in catCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
// Insert number of catches to div titled "(catname)-catch"
$('#' + [i] + '-catch').html(
"<a href='http://flickr.com/photos/46206266#N05/tags/" +
strippedTag + "/'>" + catCounts[i] + "</a>");
};
}
});
// Insert total dragged onto page.
$('#total-dragged').html(data.photos.total);
// Insert photos onto page.
$('#latest-catches').html(photohtml);
// Add tooltips to the images from Flickr.
$('img').each(function() {
$(this).qtip({
style: {
name: 'wtcdin'
},
position: {
target: 'mouse',
adjust: {
x: 8,
y: 10
}
}
})
});
});
});
UPDATE 1: I contacted the domain name company, their advice was basically "don't use JavaScript". Still can't see why it would work under one domain name and not another... Could it be to do with the fact that they "forward" the domain by means of a frame?
The browser will block AJAX requests that are sent outside of the domain that the script is hosted on. This is most likely the cause of your problem from the sound of things.
EDIT: I've found the problem, you have console.debug() calls in your script. This method is defined by the Firebug Console which is why it's only working while the Console is active. Try removing any calls to console.debug() and see how it goes.

Categories