transfer js var without php - javascript

in index.html background is changing randomly when you open it
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
in other pages i don't need to change background but use one from index.html
how can i save one var value from index.html and use it in other pages without changing?

You can use cookies or localStorage or even better sessionStorage.
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i = Math.floor(Math.random() * imgArr.length);
//fewer harcoded values is better :-)
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
sessionStorage.setItem("bg", imgArr[i]);
Of course you should check if storage is available before attempting to access it, but it will be available in modern browsers.

The easiest way would be to jsut set a default in the CSS - your JS would then override that on index.html, and if you omit the js from the other pages then it will revert to the default.
You could also use JS to set a cookie and then read from that but then youd still need to plan for if someone accesses page without having the cookie set, so id probably go with the CSS option were I you.

If you are using any server side language then try SESSION to store the value.
If you are using only client-side language then try using cookie or pass the value through parameter to the next page.

You can add some element to index.html and check in your javascript if it exists it will mean that you are on index.html page and you should change background. For example add
<div id="iamindex"></div>
And you javascript:
if($('#iamindex').length) {
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
}

Related

Is there a way to use javascript to change the css of multiple html files?

Im using this code, it only affects the file (my settings.html file) where i change the value of the background color:
function background() {
`var x = document.getElementById('color').value;
document.body.style.backgroundColor = x;
}
color is the id of the input.
But how can i affect multiple html files with this?
Every time you navigate to another page, your HTML and JS script will be refreshed, and therefore you will lose your changes.
A possible solution is to use a cookie or the browser's localStorage in order to save the value of the desired color. Then, it can be reused when navigating pages.
Example of setting a cookie using JS:
https://www.w3schools.com/js/js_cookies.asp
Example for localStorage:
https://www.w3schools.com/jsref/prop_win_localstorage.asp
Hope this helps!
You can import the JavaScript file into multiple HTML files:
<script src="filename.js">
Then run the function in said HTML Files.
Also make sure there is one "color" Id in each HTML File.

Change <div> background image with javascript

I've this in my html file
<div class="change">
<div id="changed" onclick="change_DImage()">New Upload...</div>
<input id="browse" type="file" onchange="ImagLoc()">
</div>
and this in javascript file
function change_DImage(){
document.getElementById("browse").click();
}
function ImagLoc(){
var x = (document.getElementById("browse").value).toString();
var ImgId = x.substr(12,6);
var NewImg = "url('./image/MyAlbum/" + ImgId + "')";
document.getElementById("dailyPic").style.backgroundImage = NewImg;
}
it's work pretty well but when I refresh my browser it'll change back to the default
for this in css file
background-image: url("../image/smokebird.jpg");
On page reload obviously image is going to reset to the original image. To keep it as it is even after page refresh you can do,
Save the image in Cookie (base 64 format), but there is a size limit since you can save small size images only.
On image select, you can save the image file remotely on your server asynchronously (using AJAX) and you can recall the image using the server session.
Javascript manipulates the only current state of the Html, not the file on server side. To handle it, you have to store state on server side, and change it both client and server side on button click.
Storing changed value on browser's cookie or local storage, and get stored one on page load is another option.
localStorage example:jsfiddle
However localStorage can be easily cleaned by user, even by mistake. I have found this answer useful about how it can be cleaned: SO link. Other drawback (if your really care about it) is a need of use Inline styling. There is attr css function but other than content usage is currently limited so I would stick to Inline styling.
I made more understandable version including your code, here:
jsfiddle, however I am not sure what this line and function suppose to do so I have removed it:
<div id="changed" onclick="change_DImage()">New Upload...</div>
Edit:
obviously second jsfiddle code will not work on jsfiddle, you need to inject it to your code.

Changing page using window.location

I don't really know what to title this. I am using jQuery so that when a user clicks a div, it transfers them to a page based off the div's class:
window.location = $(this).attr('class');
Say I'm connecting from the webserver (localhost). The first click may bring me to
localhost/info
If I click on about, it will bring me to
localhost/info/about
I was wondering how to get it to transfer me to
localhost/about
instead of
localhost/info/about
Firstly, location is an object. While assigning to it does work, it's better to assign to location.href.
Also, class is a bad choice of attribute to use for this, since it's very limiting. Instead, you should consider a data attribute:
<div data-href="/about"></div>
Note the / in the attribute value. That's what you need to make requests relative to the domain. Now you get there:
location.href = this.getAttribute("data-href");
PS. Every time someone writes $(this).attr(...), a unicorn dies.
You need to use an absolute path instead of a relative one. To do that you can prepend a / to the class.
window.location = "/" + $(this).attr('class');

User sets BackgroundImage. Store image url in cookie so it loads on next visit

I am working on a website:
http://tawfiq-aliyah.co.uk/epic/Site2/
I want the user to be able to set the BackgroundImage. I have implemented this with the pop-up menu in the bottom left hand corner already. But what I want is for the data about the users choice of background image to be stored so that when they come back to the site or move to another page on the site it loads the same background image.
I have looked into java cookies on the w3schools.com website
w3schools.com/js/js_cookies.asp
I have looked at the example but I am not sure how to get the cookie to store the backgroundImage of the instead of storing a username.
Any help would be much appreciated.
Thanks
In the click handlers for the thumbnails in the background image selector you do things like this:
onclick="main.style.backgroundImage='url(images/back3.jpg)'"
If you replace that with a function:
onclick="setBackgroundImage('images/back3.jpg')"
and then
function setBackgroundImage(url) {
main.style.backgroundImage = 'url(' + url + ')';
setCookie('BG', url, 100); // Or however many days you want.
}
And then, in an onload handler, do something like this:
var bg = getCookie('BG');
if(bg)
main.style.backgroundImage = 'url(' + bg + ')';
You might want to do more sanity checking on the cookie value though, you have a list of available backgrounds kicking around so you could just check that bg is defined and that it is in the list.
Also, you might want to use absolute URLs for your images rather than relative ones, that makes it easier to move things around.
I've never worked with cookies in javascript, but looking at the w3c exampple you provided, wouldn'nt it be fine to use that technique and just store the url instead of the username? And then set the img:src or background-url or what ever you are using to that url from the getCookie function? (or later, whenever the dom is ready).
An alternative could be to use local storage, but it might be overkill for what you are trying to do.

In firefox, how can I change an existing CSS rule

In firefox, I have the following fragment in my .css file
tree (negative){ font-size: 120%; color: green;}
Using javascript, how do I change the rule, to set the color to red?
NOTE:
I do not want to change the element.
I want to change the rule.
Please do not answer with something like
...
element.style.color = 'red';
What you're looking for is the document.styleSheets property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE.
For example, try pasting the following in FF for this page and pressing enter:
javascript:alert(document.styleSheets[0].cssRules[1].cssText)
For me that yields the string "body { line-height: 1; }". There are methods/properties that allow you to manipulate the rules.
Here's a library that abstracts this interface for you (cross-browser): http://code.google.com/p/sheetup/
function changeCSSRule (stylesheetID, selectorName, replacementRules) {
var i, theStylesheet = document.getElementById(stylesheetID).sheet,
thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules;
for(i=0; i < thecss.length; i++){
if(thecss[i].selectorText == selectorName) {
thecss[i].style.cssText = replacementRules;
}
}
};
You can change CSS rules in style sheets through the CSS Object Model (currently known as DOM Level 2 Style). However, if you literally have "tree (negative)" in your style sheet that rule will be dropped and not appear in the Object Model at all.
As there is no HTML element tree I am going to assume that tree is the id or class of another element.
You would first retrieve the DOM element by id:
var tree = document.getElementById("tree");
Now tree represents your DOM element and you can manipulate it any way you like:
tree.style.color = "red";
Here is a great reference for mapping css properties to their javascript equivalent.
I'm not sure you can do actual class/selector overrides. You would need to target each element that used the .tree class and set the CSS. The quickest and easiest way would be through jQuery (or another similar framework):
$('.tree').each(function() { this.style.color = "red"; });
You could even use the built-in CSS functions:
$('.tree').css('color', 'red');
(I did it the first way to show you how standard JS would do it. The $(...) part is jQuery for selecting all elements with the .tree class. If you're not using jQuery, you'd need alternative code.)
If tree is an ID, not a class (there should only be one on the page) so using getElementById should be fine. Your code should look like the other answer.
for( var i in document.getElementsByTagName("tree") ){
document.getElementsByTagName("tree")[i].style.color = "red";
}
As I said in another answer's comment, I've never seen this done how you want. I've only ever targeted elements the same way as the CSS renderer would and changed each element style.
I did see this though: jQuery.Rule
It sounds like it does what you want but the demo causes my browser to flip out a bit. I'd invite you to look at the source to see it really does do what you want, and if you want to use it without jQ, use it as a starting point.
Edit: yes this should work. It works by appending another <style> tag to the page and writing out your overrides within. It's fairly simple to follow if you wanted to port it to plain JS.
For debugging, you can use Firebug to change the CSS rules on-the-fly.
If you want to change the rendered css rules from one page request to the next then some sort of server-side scripting will be required. Otherwise the original style sheet would simply reload at the next page request.
If you want to use an event on the first page to force the server-side action then you can use AJAX to actually change the CSS rule for the user.
"I want to change the rule so that
when I navigate to the next page, I
don't have to make all the changes
again."
It sounds like what you might want then is a remote request ("ajax") back to the server with the request you want to make, and generate a dynamic stylesheet which is sent back to the client?
How/why is this Firefox specific?
I want to change the rule so that when I navigate to the next page, I don't have to make all the changes again.
There are two approaches I can think of here. Namely client side and/or server side.
Client side:
Store the theme setting into cookies and load them up next time by javascript.
Server side:
If your site have an login system, you may also store the user preference into the database and generate the webpages with this inforamtion in mind next time on.
Utimately, you are still writing things like element.style.color =. But, they should get what you want.

Categories

Resources