Injecting an image if the image doesn't already exist with jquery - javascript

I'm trying to do the following:
Check if a div contains the text "Correct Mistakes" if it does then it should:
Check if the div contains an image and/or an image with a specific URL
If the image exits and/or has a specific URL do nothing.
If the image doesn't exist and/or doesn't have a specific URL then insert it after the h3 header tag
See the code below:
var imgURL = "https://i.imgur.com/umCv9Ck.png"
$('.container .modal .content').each(function() {
if ($(this).find('h3').text() == "Corrected Mistakes") {
if ($(this).find('img').attr('src') != imgURL ) {
console.log($(this).find('img').attr('src'))
$('<img alt="blue tile" src="https://i.imgur.com/umCv9Ck.png">').insertAfter(".container .modal .content h3");
}
}
});
Currently it's inserting the image over over and over, every time I run the code... it shouldn't because on the first run it adds the image so on future runs it should see this and not add it again.
I've tried using :contains, I've tried doing it in one statement as shown below
if ($(this).find('h3').text() == "Corrected Mistakes" && ($(this).find('img').attr('src') != imgURL) {}
But nothing I try seems to be working... it's going to be something simple that I am missing but I can't figure it out.

I think part of that is the way your are using the selectors. You did not post the HTML. You can try what is below and edit accordingly. Do you want to insert a new image element or replace the one that is there or change the src for the one that is there ?
var imgURL = "https://i.imgur.com/umCv9Ck.png";
$('.container.modal.content').each(function() {
if ($(this).find('h3').text() == "Corrected Mistakes" && $(this).find('img').attr('src') !== imgURL) {
$('<img alt="blue tile" src="https://i.imgur.com/umCv9Ck.png">').insertAfter($(this).find('h3'));
}
});

Related

How can i create and add an image to my page on click?

Im adding a small function to my page where when you click a button it adds the corresponding image on the page after a certain class.
I have tried several approaches to this 'basic' problem. i have been working on this problem for two days now with no luck.
After clicking my buttons to get some interaction, I quickly recieve the 'Aw, Snap!' error from google. I know my computer can handle grabbing few images and displaying them on the page.
here is a part of my code thats most likely causing the trouble. Ive tried taking this part out of my code out and it helped. I didnt get the error message anymore, but it obviously stopped performing what i wanted it to.
var elem;
function placeImg(type) {
//creates and sets attributes for an img
elem = document.createElement("img");
elem.setAttribute("src", type+".png");
elem.setAttribute("height", "50");
elem.setAttribute("width", "40");
elem.setAttribute("alt", type +' logo image');
//puts image after the class original, its an input area
//there is only one class tag with the name original
$('#original').after(elem);
}
// when an ids with these names are clicked
$("#arrow, #barber, #gas, #lion, #none").click(function() {
//checks if the current input area has a length of 12 or less
if($('#'+findCurrentEditor()).val().length <=12){
placeImg(this.id); //places the image somewhere
}
});
Id appreciate anyone willing to try and help.
Thanks!
I only help you in creating image with jQuery and add it into a div by clicking a button. The rest, you can figure it out since it just some common logic.
$(".btn").on("click", function() {
var $image = $('<img />').attr({
src: 'https://c7.staticflickr.com/6/5820/30597229222_119e91f7e4_k.jpg',
height: "300",
width: "400"
})
$("div#img-wrapper").html($image);
});
see DEMO

Using JavaScript to dynamically change display style in img tags

I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}

Target slides by z-index and assign class

here is what I am trying to achieve. On this page http://livinginspace.staging.wpengine.com/ there are four sharing buttons. First three work perfectly fine, but the houzz works only for one image. What I am trying to achieve is to dynamicly change the button's href attribute depending on the current slide, so when you press it you are sharing the slide that was on the screen when you pressed the houzz button.
As I noticed, all you need to change inside the href of the button is the image url. Also, the only thing that changes (at least that I've noticed) is the z-index of the li element inside the slider div.
Here are my steps:
//first I am targeting the li with z-index 20
var currLi = $('li').filter(function() {
return $(this).css('z-index') == 20;
});
//then i target the url of the image inside that li
var imgUrl = $(currLi + '>div.slotholder>img').attr('src');
//finally I put the url into the houzz button
$('a.sb_network_button.houzz').attr("href", "http://www.houzz.com/imageClipperUpload?link=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F&source=button&hzid=4036&imageUrl=" + imgUrl + "&title=Product+Title+as+it+will+be+seen+inside+Houzz&ref=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F");
Altogether that is:
jQuery(document).ready(function($) {
var currLi = $('li').filter(function() {
return $(this).css('z-index') == 20;
});
var imgUrl = $(currLi + '>div.slotholder>img').attr('src');
$('a.sb_network_button.houzz').attr("href", "http://www.houzz.com/imageClipperUpload?link=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F&source=button&hzid=4036&imageUrl=" + imgUrl + "&title=Product+Title+as+it+will+be+seen+inside+Houzz&ref=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F");
});
I am pretty new to jquery, and I can't remember all the things I've tried but I have done everything I can and it still doesn't work. Also, I have noticed that when I put the code at the very end of the footer, it doesn't work at all (tried putting alerts, just to test), but when it's in the header or beginning of footer (before all other scripts) the alerts work, but I believe the problem might be that the actual li elements that I am trying to target are not yet created. Please help me with it, I've spent so many hours trying to figure this out.
Thanks a lot
To get the "li" with z-index of 20 you can do this, which will get the image URL inside of that "li":
var imgUrl;
$('li').each(function() {
if($(this).css('zIndex') == 20) {
imgUrl = $(this).find('img').attr('src');
}
});
-------------------------------------EDIT---------------------------------------------
I have made a JSFiddle that successfully gets an image src and then places it has the href on an a tag. See it here
The code is below (including the code above that I already had for finding the imgURL of the image with z-index of 20). Obviously, I am using two buttons in my example, but just for testing that the href is undefined initially, to set the href, then check it again.
$('#btn').click(function() {
//Get image with z-index = 20
$('li').each(function() {
if($(this).css('zIndex') == 20) {
imgUrl = $(this).find('img').attr('src');
}
});
$('.a').attr('href', imgUrl);
});
$('#btn2').click(function() {
alert($('.a').attr('href'));
});

Image not displaying in span

Here is my span in html
<span id="spProgress" runat="server"></span>
Now i have 2 javascript functions, one to display a loading indicator
function DisablePage()
{
document.getElementById('<%= spProgress.ClientID %>').innerHTML="<img src='Images/updateProgress.gif' />";
}
Another function to hide it.
function EnablePage()
{
document.getElementById('<%= spProgress.ClientID %>').innerHTML='';
}
When i click a button it works perfectly fine on local system.But when i put it on production server the image is not displayed.I have checked the image url but its perfectly fine.
The surprising thing is that when i click on the button it does'nt display but if i download a file from my web application, then after that the image starts displaying properly.
Here is my client script code for download
function hidePage()
{
eraseCookie("DStatus");
EnableMe();
}
function EnableMe()
{
var hddCdrDownloadRecordsLimit='<%=this.hddCdrDownloadRecordsLimit.ClientID %>';
var hddTotalCount='<%=this.hddTotalCount.ClientID %>';
if((document.getElementById(hddCdrDownloadRecordsLimit).value) < (document.getElementById(hddTotalCount).value))
{
DisablePage();
document.getElementById('<%=this.btnSearch.ClientID %>').disabled=true;
}
else
{
DisablePage();
}
var downLoadStatus = readCookie("DStatus");
if (downLoadStatus == "Completed")
{
EnablePage();
document.getElementById('<%=this.btnSearch.ClientID %>').disabled=false;
}
else
{
setTimeout("EnableMe()", 6000);
}
}
You should try to load image at page load, putting your image tag inside span and just work with "show" or "hide" that element.
<span id="spProgress" runat="server" style="display:none;"><img src='Images/updateProgress.gif' /></span>
Create a function that changes the style of span element to show (display:block) or hide (display:none).
Hope that help.
have you check that the html is being appended into the span? I would use CHrome or firebug to inspect the element and then click on the open url in new tab to see the full url it is using for the image. It could be that it has the wrong directory online and you need to but ./Images first etc

Javascript image gallery

I am looking for a javascript function that works based around an array of dynamically generated images. At the moment I have a preview window.
When this is clicked I would like it to hide the preview window and load the first image in the array. I would the like to be able to navigate through the remaining images in the array.
If someone could point me in the right direction or if you know how to put this together it would be much appreciated. Thanks.
You could dynamicly create an image element and keep on using that, something like this? (this is using jQuery).
<button id='nextImage'>Load nect image</button>
<div id='imageContainer'><div id='previewWindow'>Preview</div></div>
//Javascript frome here (JQuery)
var images = Array();
images.push('url/to/image.jpg');
window.lastImage=-1;
$('#previewWindow').click( function() { ('#nextImage').click(); });
$('#nextImage').click( function() {
window.lastImage += 1;
if(typeof(images[window.lastImage]) == 'undefined') { return; } //if endof array
$('#previewWindow').remove(); //better is to only do this once
$('#image').remove(); //Only creating an image once is even better
$('<img />')
.attr('id', 'image')
.attr('src', images[window.lastImage])
.appendTo('#imageContainer');
});
EDIT
Just read you would like to able to click the preview window, added that.

Categories

Resources