JS: Getting an image based on the page URL - javascript

Please forgive my ignorance; I'm an HTML guy and JS is pretty alien to me. I'm trying to create a function that would display an image based on the page URL.
For example: "page_001-e.html" would display "page_001.jpg"
I've managed to butcher this together so far.
<script type="text/javascript">
document.write("<img src=\"photos/full/"+location.pathname.substring(location.pathname.lastIndexOf("/") + 1)+".jpg"+"\" />");
</script>
Which returns:
<img url="photo_000-e.html.jpg" />
I need to trim -e.html from the result. I'm working in a multilingual site so I can't rely on the -e to be a constant as it's the language indicator.
From Googling, it looks like I could use str.replace or maybe slice but what I don't know is how to use them nor where to go from here.
I'd appreciate any help, or any advice if I'm looking at this the wrong way.

You can get the URL to the image with the following code, assuming there will always be a single dash:
<script type="text/javascript">
var img_url = window.location.href.split("-")[0] + ".jpg";
</script>
Now, you need to figure out where you want to place it. I recommend making an Image object, and then appending it to a particular area in the DOM.
<script type="text/javascript">
// Get the image URL
var img_url = window.location.href.split("-")[0] + ".jpg";
// Create an image (not visible anywhere)
var img = document.createElement("img");
// Set the Image to load from your new URL
img.src = image_url;
// Add it to your HTML
document.getElementById("some_id").appendChild(img);
</script>
<div id="some_id">
</div>
In the above code, the javascript will add the image to the div with ID "some_id".

You can use the below code to trim the value
location.pathname.substring(location.pathname.lastIndexOf("/") + 1).replace(location.pathname.substring(location.pathname.lastIndexOf("/") + 1).lastIndexOf("-"),"")

try with .replace ?
var path = location.pathname.replace('.html','.jpg');
document.write(path);

Related

Cannot append image with jquery

I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var img = document.createElement("img");
img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';
}
the code that works right now that I dont want to use is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var $body = $('body');
$body.addClass('campaign');
}
How can apply what I do know that works to what I am trying to get to work?
If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:
Javascript Code
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var body = document.getElementsByTagName("BODY")[0];
var img = document.createElement("img");
img.className = 'img-responsive'
img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
body.appendChild(img);
}
You can add a <img> to any element using the jQuery .append() function in the following way:
var imageToAppend = '<img src="http://example.com/img.png" height="200" width="200"/>';
$('#myElementId').append(imageToAppend); //This will append you HTML to the div with id "myElementId"
You can read more about this here: http://api.jquery.com/append/
Happy coding! =]
You should use the element where you need to append (prepend) the image element so the code will look something like:
$("base element selector").append(img);
but you need to consider that the address of the image source may not be correct from the browser point of view - consider the page is hosted in application like http://server.com//applicationgroup/applicationroot/Content/Images/.....jpg may not be pointed with ~/Content/Images/.....jpg you rather need to translate the address to the full server address on the server side.
In my case I just had to remove "~" from:
<img src="~/assets/icons/ic_chevron2.svg" class="rot-90" />
resulting in:
<img src="/assets/icons/ic_chevron2.svg" class="rot-90" />

editing html with embedded PHP using javascript

I hope someone has an answer for me,
I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php
src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>
what I would like to do is using js, dynamically update the src on a mouse click.
something like eg.
var imgSwitch = function(i){
Document.getElementById('js-img').src = "images/shop/
<?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}
Even to me this seems wrong which is why I've turned to the GURU's here
Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated
I am trying to figure out what you are asking, and I think this is your way to go:
var imgSwitch = function(i){
document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}
The change is in the i, you have to cut the string and add it as a variable.
But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.
A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.
In the function we pass the id as a parameter (onclick(changeSrc(this.id))) and we manipulate the src using the getElementById as we have the id.
<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />
<script>
function changeSrc(id) {
document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>
http://jsfiddle.net/tq1Lq5at/
Edit 1
You're using Document when it should be document, notice the lowercase d.

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

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.

Mouseover ajaxload script

Im attempting to create a mouseover event for pictures on a page to load a summary of that picture into a div container called "contentarea". I'm new into coding, so please forgive my inaptitude. The code is below, but im not sure its going to work. Basically, I have 5 pictures of dogs on a webpage, and I want the mouseover event over a picture of the dog to load information from a seperate page called "content.html." The content that is loaded should load from a that has the same ID as the ID of the picture that is cursor is currently hovering over. The content will then load into a div that is below all the pictures called "contentarea." All pictures belong to the class dog. I had tried to adapt someone else's code, but to no effect.
<script>
function(){
$(.dog).mouseover(function(e) {
var dogId = $(this).data('id');
$("contentarea").load("content.html
# " + dogId + " ");
});
</script>
You can actually load another html file using ajax, that is not a problem like zongweil said on his comment, because the content you are loading is not dynamic.
You need to add to specify that .dog is a string by using '. Additionally, please explain what you are trying to achieve using the # dogId. Are there anchors on the html file that you are loading? I don't think you will achieve the expected effect by adding the anchor to the loaded html. If you want to load the info of just one dog, then create several content.html file each with the proper id like content1.html, content2.html, etc and use this:
<script>
$('.dog').mouseover(function(e) {
var dogId = $(this).data('id');
$("#contentarea").load("content" + dogId + ".html");
});
</script>
or instead use a single HTML file with the proper ids:
<div id="dogcontent1">
TEXT TEXT TEXT
</div>
<div id="dogcontent2">
TEXT TEXT TEXT
</div>
and then on the script use this:
<script>
$('.dog').mouseover(function(e) {
var dogId = $(this).data('id');
$("#contentarea").load("content.html #dogcontent"+ dogId );
});
</script>

automatically make an image source (src=" ") a snapshot from its link with HTML, CSS, and/or javascript

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.

Categories

Resources