Change background image of a div - javascript

I have 4 pages. for example: here.com/, here.com/page1/, here.com/page2/, here.com/page3/
all 4 pages is using the same template (i didn't write the template), and it has a top box with a background image. something like this:
<div id="topbox">some text here</div>
the css:
#topbox {background:url('path/to/image/here.jpg') no-repeat};
Problem is all 4 pages is using the same image since it has the same id #topbox, and I'm not able to go in and change the structure of the pages.
Is there a way that I can use js to detect the url path, say if it's at root then background will be defaultpic.jpg, if /page1/ will use picture1.jpg, /page2/ will use picture2, /page3/ will use picture3.jpg

From the information you've given, I'd suggest:
var pagePicture = {
'page1' : 'picture1',
'page2' : 'picture2',
'page3' : 'picture3'
}
var page = window.location.pathname.replace(/^\//,'').split('/').shift();
document.getElementById('topbar').style.backgroundImage = (pagePicture[page] || 'default') + '.jpg';
References:
Array.prototype.shift().
HTMLElement.style.
Location API.
String.replace().
String.prototype.split.
Window.location.

follow the below steps. hope it will help you as a guidance.
get the page URL using:
var currentPage = document.URL;
use the above url string to identify your particular page (you may need to use substring() to extract it.)
use switch/case or conditional block to assign the correct image to correct page.
shouldn't be that complex.

Used js detection isn't a good choise apart if you can't modify your div (unique include).
In case when you can add class in your div:
<div id="topbox" class="page1">
And in your CSS:
#topbox.page1 {background:url('path/to/image/picture1.jpg') no-repeat};
Repeat this procedure for all your pages.
JS detection case :
<script type="text/javascript">
window.onload = function() {
var path= window.location.pathname.split( '/' );
var page = path[path.length - 1];
var matchPageNumb = page.match(/([0-9]+)/g);
if( matchPageNumb.length ) {
var node = document.getElementById('topbox');
if( node !== null ) {
var bgURL = "url('path/to/image/picture" + matchPageNumb[matchPageNumb.length-1] +".jpg') no-repeat";
node.style.background = bgURL;
}
}
}
</script>

Below code should do what you want:
function getPictureForPage() {
var url = document.URL; // for example: http://www.here.com/page2/mypage.html
var page = url.substring(20).split('/')[0]; // Stripping 'http://www.here.com/' from the url, then splitting on '/' to split the remaining url, and get the first element ('page2')
switch (page) {
case 'page1':
return 'picture1.jpg';
case 'page2':
return 'picture2.jpg';
case 'page3':
return 'picture3.jpg';
}
return 'defaultpic.jpg';
}
document.getElementById('topbox').style.background = "url('" + getPictureForPage() + "')";

I was able to get it to work, by inserting another css file after the existing one - to only the page i want to change the bg, and it overwrite the existing 'topbox' class.
#topbox {backgroundurl('path/to/image/file.jpg') !important;
running out of time, but this work. not sure if this's the right way to do it, but it works ... for now. i'll visit back and use the codes was provided here and apply to the page.
thanks for all your help,

As you are unable to go to the html, you can get this solved by 2 ways.
Add class to div with id topbox dynamically from js file depending on the url and applying background css to respective class.
jQuery Code
var url = window.location.pathname;
var divCls = '';
switch(url) {
case 'here.com/page1/': divCls = 'page1';
break;
case 'here.com/page2/': divCls ='page2';
break;
case 'here.com/page3/': divCls ='page3';
break;
case 'here.com/page4/': divCls ='page4';
break;
default: divCls ='page';
break;
}
$("#topbox").addClass(divCls);
CSS
#topbox.page1 { background-image: url(../page1.jpeg); }
#topbox.page2 { background-image: url(../page2.jpeg); }
#topbox.page3 { background-image: url(../page3.jpeg); }
#topbox.page4 { background-image: url(../page4.jpeg); }
Directly applying the background image from javascript
jQuery Code
var weburl = window.location.pathname;
var chksplit = weburl.split('/');
switch(chksplit[0]) {
case 'page1': $("#topbox").css("background-image": "url(../page1.jpeg)");
break;
case 'page2': $("#topbox").css("background-image": "url(../page2.jpeg)");
break;
case 'page3': $("#topbox").css("background-image": "url(../page3.jpeg)");
break;
case 'page4': $("#topbox").css("background-image": "url(../page4.jpeg)");
break;
}

Related

Replacing iframe source with Javascript - Can I use a loop?

I have a list of items (districts) on a page, and an iframe pulling in a map on the same page. When a user clicks on one of the districts, the JavaScript changes the source of the iframe to show a map of the district the user clicked.
My current code simply uses an "onclick" for each district, which then calls a function to change the source of the iframe.
I am wondering if I can simplify this code at all, possibly by using a loop? If I have 15 more districts to add to the page, will I have to add another "onclick" and another function for each one? Or is there an easier way that I am missing?
Simplified HTML:
<div id="districtlist">
Allen
Barren
Butler
<!--about 15 more links to follow-->
</div>
<iframe id="maparea" src="http://www.reddit.com"></iframe>
Javascript:
var a = document.getElementById("districtlist")
a.getElementsByTagName("a")[0].onclick = Allen;
a.getElementsByTagName("a")[1].onclick = Barren;
a.getElementsByTagName("a")[1].onclick = Butler;
//more lines...
function Allen() {
document.getElementById("maparea").src="http://www.youtube.com";
}
function Barren() {
document.getElementById("maparea").src="http://www.mentalfloss.com";
}
function Butler() {
document.getElementById("maparea").src="http://www.amazon.com";
}
//more functions...
I believe you could try this
var elems = document.getElementById("districtlist").querySelectorAll('a');
[].forEach.call(elems, function(elem) {
elem.onclick = function() {
var url = '';
switch(elem.innerText) {
case 'Allen':
url = "http://www.mentalfloss.com";
break;
case 'Barren':
url = "http://www.mentalfloss.com"
break;
case 'Butler':
url = "http://www.amazon.com";
break;
}
document.getElementById("maparea").src=url;
}
});

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

javascript: multiple stop image toggle

I am trying to make an image button on my website toggle wallpaper change frequency options (off,5,10,15,30,30,90 minutes). I have created a custom image for each step (so the user can be aware of the current setting). When implemented the user should be able to repeatedly hit the button to toggle through all 7 options, ultimately looping back to the beginning.
I have some code to swap between two images (below), and have used it for other options on the site (wallpaper on/off), but I just can't figure out a way to get the code to work for my new needs.
if (imageId == 'image1') {
if (document.getElementById) {
var img = document.getElementById(imageId);
img.src = (img.src.indexOf("40_unlocked.jpg") != -1) ? "40_locked.jpg" : "40_unlocked.jpg";
}
}
I expect I will need to determine the current image, then use a switch to advance to the next option, something like the below, but I don't know how to determine the current image - hoping someone can offer a suggestion - thanks in advance!
function changeIt(img) {
var src;
switch (img.id) {
case "example":
src = "n.gif";
break;
case "example2":
src = "n2.gif";
break;
case "example3":
src = "n3.gif";
break;
}
img.src = (img.src.indexOf("jj.gif") < 0 ? "jj.gif" : src);
}
This should get you started
Name your images n0.gif through n6.gif.
toggle.onclick=function(){
//isolate the number of the current image
var num=this.src.split('.gif')[0].split('n')[1]-0;
//add 1 and take mod 7 to loop it back to 0 if it needed
num=++num%7;
//set the src to the new image
this.src='n'+num+'.gif';
}
Try creating an array of all of the src urls & then toggle it like this.
function changeIt(img)
{
var src=img.src;
images=['src1','src2','src3','src4','src5','src6','src7'];
index=images.indexOf(a);
if (index+1>6)
{
index=0;
}
else
{
index+=1;
}
img.setAttribute('src',images[index]);
}

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

Javascript to redirect from #anchor to a separate page

I have a set of links with #anchors pointing to a single webpage and I would like to smoothly move to a model with a separate webpage for each of those links. I want the old links to keep working using a redirect.
Old link style:
/all_products#A
/all_products#B
/all_products#C
New link style:
/products/A
/products/B
/products/C
I know that the server does not receive the #anchor name in the request but Javascript might.
Is it possible to automatically redirect from /all_products#A to /products/A using Javascript?
JQuery would be fine, it's being used on the site anyway.
I added this new answer to include some best practices for both extracting the hash from the url and doing a redirect.
// Closure-wrapped for security.
(function () {
var anchorMap = {
"A": "/products/A",
"B": "/products/B",
"C": "/products/C"
}
/*
* Best practice for extracting hashes:
* https://stackoverflow.com/a/10076097/151365
*/
var hash = window.location.hash.substring(1);
if (hash) {
/*
* Best practice for javascript redirects:
* https://stackoverflow.com/a/506004/151365
*/
window.location.replace(anchorMap[hash]);
}
})();
Put this as close to the top of your HTML <head> as you can so that it can execute before the rest of the page resources download:
<script>
function checkURL() {
var old_path = '/all_products';
if (window.location.pathname != old_path) {
// Not on an old-style URL
return false;
}
// Some browsers include the hash character in the anchor, strip it out
var product = window.location.hash.replace(/^#(.*)/, '$1');
// Redirect to the new-style URL
var new_path = '/products';
window.location = new_path + '/' + product;
}
checkURL();
</script>
This will check the current page URL and redirect if it matches the old-style path.
This code makes use of the window.location object which contains all the parts of the current URL already split up into component parts.
Making this script more generic is left as an exercise for the implementer.
I hope this can help :)
var urlSplit = document.URL.split("#");
if (urlSplit[1]) {
location.href = "http://www.example.org" + "/" + urlSplit[1];
}
else {
location.href = "http://www.example.org";
}
With jquery, either just replace the href with the correct one:
$('a').each(function() {
this.href = this.href.replace(/all_products#/, 'products/');
});
or capture clicks and redirect:
$('a').click(function() {
window.location = this.href.replace(/all_products#/, 'products/');
return false;
});
this might help:
A
B
C
D
E
<script type="text/javascript">
function redirectMe(a){
var aa=a+"";
window.location=aa.replace(/#/g,"/");
}
</script>

Categories

Resources