How to change an image on a site using XML data & jQuery - javascript

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.

Related

Javascript that automatically fills in HTML file path for images

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.

getElementById from another page

I am trying to get one div from one webpage URL to another webpage and display in plain text using getElementById without using AJAX or jQuery because I'm going to implement it in FitNesse. Is there a way to pass the URL?
You could load the URL in a hidden iframe.
Then use iframe.contentWindow.document.getElementById($id) as outlined here: How to pick element inside iframe using document.getElementById
Something along the lines of:
<iframe src="urlWithinYourDomain.html" style="display:none"></iframe>
Followed by a function something like:
var divElement = document.getElementById('iframeId').contentWindow.document.getElementById('elementIdOnSourcePage');
document.getElementById('targetParentId').appendChild(divElement);
I'm afraid I can't test this at the moment, so there may be syntax errors, but I think it conveys the idea. It's a bit of a dirty approach, but given your constraints it's the best way I can see to do what you're asking.
On page 1.
<div id="dataDiv">1234</div>
<a id="getData" href="">Page2</a>
<script>
var data = document.getElementById('dataDiv').innerHTML;
//This will get the content from the div above with the id of "dataDiv"
document.getElementById("getData").setAttribute("href","page2.html?var="+data);
//This will set the url of the anchor with the id of "getData" with your url and the passing data.
</script>
And on page 2
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var var1 = getUrlVars()["var"];
This will send the content in your div on page one to page two. the result url on page 1 will be page2.html?var=1234

Change img tag using jquery from a list of items and an url stored in an item

I have a list of items displaying a link in my view like this:
#Html.ActionLink(cardPackInfo.mCard.mMasterCard.mCardName, "ViewItemDetails", "Item", null, new { #class = "cardImage", #data_id = cardPackInfo.mCard.mMasterCard.mCardImageLink})
As you can see, I'm trying to store a data in a kind of #data_id like I did.
I have a field dedicated to display an image:
<div id="image">
<img id="cardImageDiv" src="~/Images/Functional/cardback.jpg" alt="defaultCard" class="nullify"/>
</div>
and my jQuery script is like this:
$('.cardImage').mouseover(function() {
var imageSrc = $(this).attr("data-id");
alert(imageSrc);
$('#cardImageDiv').attr('src', imageSrc);
var newImage = $('#cardImageDiv').attr('src');
alert(newImage);
});
So what I'm trying to do is, when the user's mouse is over one of the link, I take the url when the image is located (which is stored in my model at cardPackInfo.mCard.mMasterCard.mCardImageLink and change the src of the current image located in the image src with the id cardImageDiv.
However the image is not changing. The two alerts are there to testify that the first data obtained is the url of the image (which may look like this: ~\Images\CardsImages\Return to Ravnica\(RTR) - 231 - NameOfTheCard.jpeg) and the second alert tells me of the current src. But the result I have is that the first image is removed and I have the small "broken link" icon. Can anyone help me out?
Can you try with the src like "/Images/etc" and lose the ~

jQuery to change element Attributes and return the edited Html Source back?

Actually what i'm doing is to find the <img> image tags and get its src attribute to change them.
I already got upto this point but the problem more is: To get the edited the html source back (to put into the database.)
To say more brief & clearly, i'm about to grab some Dynamic Html Containers and then change the image paths and save the whole source chunk back.
For brief example if i search inside $(div.container).html() on this:
<div class="container">
<..> .. </..>
<..>
<img src="images/apple.jpg" />
<..>
<img src="images/banana.jpg" />
</..>
</..>
</div>
Firstly, lets say <..> represent any of not previously knowable html tags.
Then i will get:
var dom_contents = $("div.container").html();
Now i got the original html source inside the target container <div>
Then lets say i need to change each <img src with sample/ for its folder. It will then be fruits/apple.jpg and fruits/banana.jpg.. etc.
I still getting some of the stuffs like:
$("div.container).each(function() {
var arr = $(this).find("img");
for (var i=0; i<arr.length; i++) {
var img_src = $(arr[i]).attr("src");
/*
* I NEED TO CHANGE THE IMAGE SRC HERE
*/
}
});
** Finally, i need to save this the whole edited html source into the database. **
So how do i change the <img src='' .. and
How do i get this whole edited html source, back from the jQuery?
Amend the source attribute for each image as follows. You don't need to write the html back. The source html will be updated:
$("div.container").each(function() {
$(this).find("img").each(function() {
$(this).attr("src", "/image/url/file.png");
});
});
To get the html source of the container, use the following:
$("div.container").html();
This will set the attribute:
$(arr[i]).attr("src", mynewsrcvalue);
Once you're done just send the innerHTML (or .html()) back in an AJAX request. But if you want this stuff in a database, why not just manipulate the source on the server side in the first place?

JavaScript - writing html elements that don't show up?

I'm trying to write some code in javascript that uses a user's cookies to display a box containing some information. The page opens with some boxes containing news articles from Google News RSS feeds. I'm using a 3rd party app for the RSS; the feed is included in the HTML code as such:
<script language="JavaScript" src="http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed" charset="UTF-8" type="text/javascript"></script>
The user can move the boxes around, and I want to store the box locations using cookies so that if a user revisits the page, the boxes will be in the same location. However, when I try to load the page from the information in the cookies, the boxes are blank. This is an example of what my code looks like (RSS feed for news using keyword "Barack Obama"):
// Render boxes into HTML
function renderItem(container) {
var wrapper = document.getElementById(container);
var div_box = document.createElement('div');
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
var div_box_feed = document.createElement('div');
var feed_script = document.createElement('script');
feed_script.setAttribute('language', 'JavaScript');
feed_script.setAttribute('src', feed_url);
feed_script.setAttribute('charset', 'UTF-8');
feed_script.setAttribute('type', 'text/javascript');
div_box_feed.appendChild(feed_script);
div_box.appendChild(div_box_feed);
wrapper.appendChild(div_box);
}
When the page loads, the box appears but the news articles from the RSS feed are not there and the box is empty. When I look at the source code, however, it is identical to the code of the initial boxes (which did display the news articles).
Does anybody know what's wrong?
Thanks!
You never declared column_div here:
wrapper.appendChild(column_div);
Did you mean:
wrapper.appendChild(div_box);
?
I believe that by default script elements created in this manner have their async attribute set to true, so the rest of your code will execute before your JS has been retrieved.
Where does the column_div variable come from?
You're missing a question mark to separate the post variables from the URL, so the URL is resolving to
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php%20src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
It should be
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed'

Categories

Resources