My website allow users to change the background image using a URL with the following code:
var defaultImage = "'#fff'";
document.getElementsByTagName('body')[0].style.backgroundImage = localStorage.getItem('back') ? "url('" + localStorage.getItem('back') + "')" : "url('" + defaultImage + "')";
function changebackground() {
var url = document.getElementById('bgchanger').value;
document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')";
localStorage.setItem('back', url);
}
I was wondering how can the current background image URL be displayed in a textbox?
DEMO: http://goo.gl/253IN
UPDATE:
This is what I would like:
function changebackground() {
var url = document.getElementById('bgchanger').value;
document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')";
// populate the input w/ the url:
document.getElementById('textfield').value = url;
localStorage.setItem('back', url);
}
However every time the page refreshes the textbox is clear. How can I save this information so it always stays in the textbox even when the page is refreshed?
Thank you in advance!
You can get the background image like this:
window.onload = function () {
var bgimage = document.body.style.backgroundImage;
var cleaned = bgimage.replace(/^url\('/, "").replace(/'\)$/, "");
var txtbox = document.getElementById("txt1");
txtbox.value = cleaned || "No background image set";
};
http://jsfiddle.net/KW852/3/
It gets the body's backgroundImage style, then strips any leading url(' and trailing ') and returns the middle text. Then, just sets the textbox's value.
How about:
function changebackground() {
var url = document.getElementById('bgchanger').value;
// populate the input w/ the url:
setBackground(url);
localStorage.setItem('back', url);
}
function setBackground(url){
document.body.style.backgroundImage = "url('" + url + "')";
setText(url);
}
function setText(url){
document.getElementById('textfield').value = url;
}
var defaultImage = "'#fff'";
bgUrl = localStorage.getItem('back') ? localStorage.getItem('back') : defaultImage;
// Set background
setBackground(bgUrl);
The only thing I added was the comment line and the line immediately following it. You already have the URL, it's just a matter of setting the input element's value.
Update
I added some code to initialize the text box when the background is first set (presumably on page load), per your additional requirement in your comment, below.
Related
I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}
I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.
var changeIt = ""
var backgroundPic = new Array(4);
backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';
var picCounter = 0;
var numberOfPics = 5;
var picTimer;
function setPic(){
alert("hi I want this pic: " + backgroundPic[picCounter]);
$('slider').css('background-image', url + "backgroundPic[picCounter]");
picCounter += 1;
if(picCounter >= numberOfPics){
picCounter = 0;
}
}
$(document).ready(function(){
$('.slider').css('background-image', backgroundPic[picCounter]);
picTimer = setInterval(setPic, 2000);
});
The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:
var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];
var picCounter = 0;
var picTimer;
function setPic() {
// note the . in the jquery object below to indicate a class selector
$('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
picCounter++;
}
$(document).ready(function() {
picTimer = setInterval(setPic, 2000);
setPic();
});
You have to set background image like this:
$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");
You inverted the positioning of the quotemarks on the second line of setPic.
Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);
On your setPic function, this line
$('slider').css('background-image', url + "backgroundPic[picCounter]");
isn't missing a dot on $('.slider')?
You'll need to include double quotes (") before and after the imageUrl like this:
$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');
This way, if the image has spaces it will still be set as a property.
function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
m.style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')";
var p = document.getElementById('image');
p.innerHTML = previewPic.alt;
}
function unDo() {
/* In this function you should
1) Update the url for the background image of the div with the id = "image"
back to the orginal-image. You can use the css code to see what that original URL was
2) Change the text of the div with the id = "image"
back to the original text. You can use the html code to see what that original text was
*/
document.getElementById("image").style.backgroundImage = "url('')";
document.getElementById('image').innerHTML = "Hover over an image to display here";
}
I suspect this is homework thus I only give you a partial answer here:
function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
// now how would I fix this string concatenation up? hmmm
m.style.backgroundImage = "url('" + previewPic.whattoplacehere +')";
// comment out as we have this var p = document.getElementById('image');
// change to m from p as we had it already.
m.innerHTML = previewPic.alt;
}
What event do we need? We need two it seems, what is the second one?
var myimage = document.getElementById("myimage");
myimage.addEventListener("mousesomething", function(event) {
var target = event.target,
related = event.relatedTarget;
upDate(what should be here?);
}, false);
Research:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Use this in JS,
document.getElementById("demo").style.backgroungImage = url(" ") ;
Images in Html are already saved in src so, previewPic.src will be images link.
Don't forget to concatenation ..
like this "url" + "(" + parameters.src + ")" ;
I have a large number of images of the same class "linkImg" and I would like them to behave as links without adding tags.
What I'm tryng is something like this:
<script type="text/javascript">
$(function()
{
$('.linkImg').click( function( event )
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
gotothelinl(linkPath, linkRel, linkTarget)// this is just a made-up function - it the part I don't know how to make work
})
} );
</script>
When it works it should behave like the tag was there with all attribute intact. I tried using location.href but I can't ad rel or target attributes to that.
thx in advance
David
To change the location of the page you'd do
location.href = "/newLocation.html"
This simulates a hyperlink (although I'm an ajax enthusiast!)
I think your are taking the problem for another angle... try this:
<script type="text/javascript">
$(function()
{
$('.linkImg').each( function()
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
$(this).wrap('<a href="'+ linkPath +'" target="' + linkTarget + '" rel="'+ linkRel + '" />')
})
} );
</script>
I need to change the href of any local link when it is clicked on.
I've worked out how to select the correct links and create the new url, but not sure how to change the location. I need to be certain that any other click events have also run, so I can't just change the location immediately.
var my_host = 'example.com';
$(document).click(function(e) {
if(e.target.hostname == my_host)
{
alert(e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
//...
}
});
This is related to my earlier question.
You can bind the event on your local links like this and use the attr method to change the href:
$('a[href*="yourdomain.com"]').click(function(){
// your code before changing href
$(this).attr('href', 'new url here');
});
Replace yourdomain.com with your own domain so that the above code only targets your local links.
This is completely untested, but should get you where you're going:
var site = "http://yourdomain.com";
// Match anchor tags with an href value that starts with your
// site URL, or that start with / which are relative URLs (also
// your site).
$('a[href^="' + site + '"] a[href^="/"]').click(function(){
var url = $(this).attr('href');
if (url.indexOf(site) != -1) {
url = site + "/#" + url.replace(site, ""); // Quick dirty way to get the path component of the URL
} else {
url = "/#" + url;
}
$(this).attr("href", url);
});
Note that I read your other question, and I personally don't understand why you would do this on a click event, instead of just replacing all the href values as soon as the page is loaded.
Credit to Sarfraz: here is the answer without the bug.
var my_host = "example.com";
$('a[href^="/"], a[href^="http://' + my_host + '"], a[href^="https://' + my_host + '"]').click(function(e){
$(this).attr('href', e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
});