Add a default image if there is not image in the container - javascript

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

Related

Replacing <img> tags with links to their content jquery

As the title says, I am having some issues converting images to links using jquery. My code right now is:
var all_img = $(".message .content").find("img");
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith($("<a href='" + src +"'>Image " + index+1 + "</a>"));
});
Which results in the images being replaced with [object Object]. I have also tried:
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Which results in the html I am trying to insert going in as plain unclickable text. Am I misunderstanding how .replaceWith() works?
You couldn't call the jQuery .replaceWith() method on value, you need to use a jQuery object, to target the current img in every iteration you need to use $(this) like :
all_img.each(function (index, value) {
var src = value.src;
$(this).replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
I think it is better to create a new element and remove/hide the img:
$('.turnInAnchor').click(function(e){
$('img').each(function(index, el) {
$('body')
.append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
el.remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />

onerror Event didn`t work

I try create code which replace src image on another. I want to use function invalidUrl():
function invalidUrl() {
paint.src = randomvariable;
}
but this function isn`t running :<
var paint = '<img src="' + url + '"class="heightImg" onerror="invalidUrl()"/>' + '</br></br>' + description;
How to change src images if current picture doesn`t exist?
paint.src // undefined
this is because paint is of "string" type and strings have no "src" property.
You can use vanilla JavaScript to build your img element:
var paintedElement = document.createElement("img");
paintedElement.src = url;
paintedElement.class = "heightImg";
paintedElement.onerror = function invalidUrl() {
paint.src = randomvariable;
};
paintedElement.innerHTML = "</br></br>" + description;
// append where you need to append paintedElement
If you're willing to use jQuery, you can create an element:
var paintelement=$('<img src="' + url + '"class="heightImg"/>' + '</br></br>' + description);
paintelement.attr('src','wherever');
paintelement.appendTo('#somewhere');
paintelement.on('error',function(){paint.src = randomvariable;});

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 + "')>";

Unable to show images in javascript

I am using javascript to show images .I have 5 images but unable to display them.My code is as follows:
function set()
{
var i;
for(i=1; i<=5; i++)
{
var image = "<img src=images/sl + i + />";
document.getElementById('slider').innerHTML = image;
}
}
setInterval("set()","500");
<div id="slider">
<img src="images/sl1.jpg" />
</div>
Change -
var image = "<img src=images/sl + i + />";
To -
var image = "<img src=images/sl" + i + "/>";
Also I believe you need to append image format in this too(jpg | png etc)
EDIT --
var image = "<img src=images/sl" + i +".jpg"+" style='width:500px;height:300px;' />";
You're always putting the same image right now, the one of end of loop. I can propose this code :
var i = 0;
function set(){
var image = "<img src=images/sl" + i + "/>";
document.getElementById('slider').innerHTML = image;
i = (i+1)%5;
}
setInterval(set, 500);
I fixed a few other bugs/problems. Never pass a string as first argument to setInterval, pass the name of the function or a function expression. And the second needed argument is a number, it doesn't make sense to pass a string literal.
But it would have been cleaner to define the img element in the HTML part of your code and just change the src property instead of the whole slide inner HTML. It would also tell to the browser to change the display only after the image has been loaded.
Assuming that the filenames of the images aresl1, sl2,..., sl5 , it should be
var image = "<img src=images/sl"+i+"/>";
Try this:
function set()
{
var i;
for(i=1; i<=5; i++)
{
var image = "<img src='images/sl" + i + "'/>";
document.getElementById('slider').innerHTML = image;
}
}
setInterval("set()","500");
<div id="slider">
<img src="images/sl1.jpg" />
</div>
Your ' i ' variable is part of your string, you need:
var image = "<img src=images/sl" + i + "/>";

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');

Categories

Resources