I'm creating an App using html 5 phonegap and one portion of the App is drawing an rss feed in. One problem i've run into is that the feed has images in it and the url for the images is set to be draw from the server the feed is located on. For example the entire img code is:
<img src="/files/2012/01/brazilsal.jpg" />
Now since those images aren't native it won't work on the app.
So i need to prepend the src to be
<img src="http://management.bu.edu/files/2012/01/brazilsal.jpg" />.
I also need it to not affect any other image on the app.
Any ideas on how to do this in javascript or jquery?
Select the images using the attribute starts with selector [attr^=value], then set it's src value using $.fn.attr.
$('img[src^="/files"]').attr(function(i,src){
return "http://management.bu.edu" + src;
});
You need js-uri.
Simple example:
var rssUri = new URI("http://management.bu.edu/data.rss");
var imgUri = new URI("/files/2012/01/brazilsal.jpg");
var fullImgUri = imgUri.resolve(rssUri);
alert(fullImgUri); // http://management.bu.edu/files/2012/01/brazilsal.jpg
Related
We have created an image gallery addon for Page builder
which displays images as gallery like so:
<img class="sppb-img-responsive" src="'.JUri::base(true).'/'.$value->thumb.'" alt="' . $value->title . '">
But the problem is that when it uses an external image link
it returns an error like in this example:
<img class="sppb-img-responsive" src="/dev/ibwintalldev/https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_1280.jpg" alt="test">
Is there any way to detect this problem so as to fix this?
Or to check if the image has an external link?
Thanks
Lahmar
Why the src tag contains /dev/ibwintalldev/, because of which image is not displaying. Remove it and try.
<html>
<body>
<img class="sppb-img-responsive"
src="https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_1280.jpg"
alt="test">
</body>
</html>
You can remove the unwanted text before https: like so in javascript:
// returns all images on page
images = document.getElementsByTagName("img")
for (let img of images) {
// replaces extra text from the src
img.src = img.src.replace(/(.+?)(?>http)/, "")
}
Regex explanation:
(.+?) matches everything (if any) up to what follows this (i.e. http) and adds to matching group
(?=http) looks ahead for pattern http (but doesn't include in matching group so doesn't get replaced)
The following shows the regex working:
let img = new Image;
img.src="/dev/ibwintalldev/https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_1280.jpg";
// we apply the regex
img.src = img.src.replace(/(.+?)(?=http)/, "")
console.log(img.src);
I'm trying to use window.location.pathname and injecting innerHTML to generate the file paths for an image so all I need to do is type fileName.png in a div in the html body and have the javascript generate the file path behind it so that it displays the image in the rendered website. This is for images that aren't stored in the same folder as the working file.
I've had mild success but it only works for one image per page which isn't very helpful.
I've gotten this code to work for one image per page:
<div class="picName">pic.png</div><div id=<"shortcut"></div>`
<script>
var relativePath = window.location.pathname;
var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
document.getElementById("matts-shortcut").innerHTML =
'<src=\'/images' + relativePath + '/' + picName + '\'>';
</script>
The solution below pulls images names from with Divs using .querySelectorAll() which returns a DOM NodeList. The NodeList is useful because it has a forEach() method that can be used to loop over each item is the list. Loop over each list item using it's textContent property as the image name. Then you'll need to create a new image element for each image. To do that you can do something similar to this.
let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
let picName = image.textContent;
// Create a new image element
let imgEl = document.createElement('img');
// Set the src attribute of the image element to the constructed URL
// the name of the picture will be the div text content
// This is done with a template literal that you can learn about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
imgEl.src = `${relativePath}/${image.textContent}`;
// Now we have a real image element, but we need to place it into the DOM so it shows up
// Clear the image name
image.textContent = "";
// Place the image in the Div
image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>
EDIT: In response to Ismael's criticism, I've edited the code slightly and commented every line so you can learn from this answer. There are two hyperlinks referenced in the code to help you think about coding in a modern way and so you can interpret modern code you read more easily.
About:
Arrow functions
Template Literals
Edit 2:
With further clarification, the answer has been amended to pull the image file names from Div elements already in the DOM.
Let ID equal your element's id
Call on:
document.getElementById(ID).src = "image_src"
When you want to change images, like an onclick action or as part of a function.
I have a site that has a banner at the top of the page. I've started to overhaul my HTML structure and am now getting various pieces of information that populate the site out of an XML file. My HTML that uses the jQuery is:
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
<script>
var root = null;
$(document).ready(function ()
{
$.get("Status_Pages.xml",
function (xml)
{
root = $(xml).find("site[name='" + exampleSite + "']");
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
var imageSrc=$(root).find("headerImage").text();
$(".PageHeader img").attr("src",imageSrc);
result = $(root).find("version");
$("td#version").html($(result).text());
result = $(root).find("status");
$("td#status").html($(result).text());
result = $(root).find("networkNotes");
$("td#networkNotes").html($(result).text());
....etc etc
});
});
</script>
My XML file looks like this.
<sites>
<site name="Template">
<headerImage>images/template-header.png</headerImage>
<productVersion>[Version goes here]</productVersion>
<systemStatus color="green">Normal</systemStatus>
<networkNotes>System status is normal</networkNotes>
</site>
</sites>
I have several <site>s that all have their own data that will populate different areas of individual sites. I've ran into some snags though.
The first snag is how it currently obtains its header image:
html
<div class="container">
<div class "PageHeader"> <!-- Header image read from XML file -->
<img border="0" src=""/>
</div>
Right now it's hard-coded to be the template header image, but I need to make that generic and read the XML value for that site. So instead of being hard-coded as images/template-header.png it would read the XML value for the current site, which is still going to be the template header - but it won't for every page.
How can I read in the image string to populate my HTML so that each site has a different image depending on what's in the XML?
Edit: Edited code to match current issue. Currently, I just get a broken image, but I can still change it back to the hard-coded image URL (images/template-header.png) and it works.
As you already have the code that can extract the image URL information from the XML, which is
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
It's now a matter of attaching that URL, to the image tag. We need to select the object, and then simply change it's src attribute. With jQuery this is actually pretty easy. It'll look something like
var root = $(xml).find("site[name='" + site + "']");
//get the image url from the xml
var imageSrc=$(root).find("headerImage").text()
//get all the images in class .PageHeader, and change the src
$(".PageHeader img").attr("src",imageSrc)
And it should work
Example
In conclusion, if you already have some values you want to put in HTML tags dynamically, it's pretty easy. There's .html("<b>bold</b>") for content, there's .attr("attrName","attrValue") for general attributes. .css("background","red") for changing CSS directly. There's also some class modifying stuff that would be useful in the future.
I have a JavaScript Image object that I load dynamically with jQuery.
What I want to do is change a <img /> image with one stored on my Image object. How should I do this?
Note: I want to avoid changing the source of my <img /> tag as it downloads it again from the server, and I already have the image stored in my image object
You mean
$('#imageToChange').replaceWith(imageObject)
?
New Image object:
var Image_off = new Image();
Image_off.src = 'first.jpg';
image src change with jQuery:
$("#my_image").attr("src",Image_off.src);
With jQuery...
have both images already on your page and show or hide either one, based on a logical condition.
Make your new image in javascript memory, and then append it after the original image, then remove the original. You may also wish to cache the original before removing it in case you would like to re-use it.
html
<img id="replace" />
js
var img = new Image();
img.src = "someUri.png";
$("#replace").after(img);
$("#replace").remove();
In my HTML document I want to create a placeholder for an image but leave the source 'To be determined' so to speak so that when I put a link on the image it will acquire a snapshot from the target website to use as the image source. If you don't quite understand what I'm saying it is as follows:
I want to create a linked Image
<img src="source">
and I want to use javascript to replace the 'source' with a snapshot of the '#' page.
I would like to use this so that on my website I can link to Youtube videos (using the link in the embed codes) and automatically acquire a thumbnail for the link without any work more than inputting the link/URL.
I am not very javascript savy so any help with that portion will be much appreciated, although I am trying to do this with very minimal Javascript if possible. All answers are much appreciated and if any more information is needed just ask.
If you want to put YouTube screenshot I recommend using jQuery with jYouTube and here how I put it together:
JAVASCRIPT:
// Run when page is load
$(function(){
// Find all <a> inside element with youTube class name
$(".youTube a").each(function(){
// Get reference to found <a> link
var lnk = $(this);
// Get YouTube thumb image for <a>'s href attribute
var url = $.jYoutube(lnk.attr("href"));
// Now update inside image's src attribute with thumbs image
lnk.children('img').attr("src", url);
});
});
HTML
<div class="youTube">
<img src="#" /><br />
<img src="#" /><br />
<img src="#" /><br />
</div>
Also I put it in jsfiddle for easy demo: http://jsfiddle.net/snyew/
I hope this helps :-)
It takes an Image object.
yourImg = document.getElementById("image_id");
var newImg = new Image();
newImg.src = //URL of the image to be acquired
yourImg.src = newImg.src;
Assuming you want to do this for every link with just an image as child, you can do:
$('a').each(function() {
if($(this).children('img').length == 1 && $(this).children().length == 1) {
// get snapshot
var snapshotImgURL = getSnapShotOf($(this).attr('href')); // replace this with your AJAX call to get the snapshot
// set it to the image
$(this).children('img').attr('src', snapshotImgURL);
}
});
The above assumes you are ok with using jQuery on the project.