Please note this is just an example:
<img src="img/normal-font.png" onclick="javascript:document.body.style.fontSize = '13px';" />
<img src="img/medium-font.png" onclick="javascript:document.body.style.fontSize = '14px';" />
<img src="img/large-font.png"onclick="javascript:document.body.style.fontSize = '15px';" />
The body text does indeed enlarge if I choose one of them, but what I like to include is remembering what option you've chosen by reading cookies.
In fact, I have no experience in creating cookies in JS, only in PHP. Could someone come up with an example of how to make cookies the simpliest way remembering my option, but whenever someone clicks another one, it should get rid of the cookie that was last set, e.g. Cookie value has 15px, then should update it or remove it with a new cookie with a new value of 13px and so on.
Thanks :)
you can set and get the cookie values from javascript in the same way you do in php.
you can use the following two methods for your help.
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
have a look into this page for more details.
This might Help:
QuirksMode Javascript cookies reference.
Related
Hello , This is the code that can change the image src and I am using it offline .It has 2 button , one of which turns on the light and other turns off it. It works well! But problem is it doesn't remember the choice i made once i reload the page. Ex. If i turn on the light , it shows the glowing bulb but forgets after reload.
Note: I have tried some online solutions but since it was about something related to javascript, it didn't seem to work.
Target is chrome only!
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.
</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off
the light</button>
</body>
</html>
As already noted you can use localStorage to store the src and load it next page load. To use this for your example you could use the following code:-
Html
<button id="btn1">Turn on the light</button>
<img id="myImage" src="off.png">
<button id="btn2">Turn off the light</button>
JS
//set src on page load
if(localStorage.imgSrc) {
document.getElementById('myImage').src = localStorage.imgSrc;
}
//set src and localStorage on click
document.getElementById('btn1').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'on.png';
}
document.getElementById('btn2').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'off.png';
}
You can use either localstorage that is being supported by the most modern browsers or use cookie.
What i would do is to check in a function if localstorage is being supported if not use cookie like this
function localStorageExists(){
try {
localStorage.setItem(simpleTest, simpleTest);
localStorage.removeItem(simpleTest);
return true;
} catch(e) {
return false;
}
}
function saveOption(value) {
if(localStorageExists() === true){
// available use local storage
localStorage.setItem(option, value);
}else{
// unavailable use cookie
createCookie("option", value, 30);
}
}
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
you can also have a function that detects and reads accordingly ;)
I have a small shopping cart to use with PHP in WordPress, but now I'm implementing it to be used in a site with AJAX.
I have a PHP function that finds some cookies that tell me what the user has put in the shopping cart, however, since now I'm loading the product info into the same div according to user selection, that function with PHP is no longer useful and need to do it with JS or JQuery in order to be updated every time the user changes to another product.
The function in PHP is:
function in_cart($post_id){
$found = false;
if(!empty($_COOKIE['cart'])){
foreach ($_COOKIE ['cart'] as $c) {
if ($c ['id'] == $post_id)
$found = $c;
}
}
return $found;
}
The cookies are called "cart[0][id]" and "cart[0][quantity]" where the "0" increments depending on how many products there are, and with that function I can just run trough all instances of a cookie that starts as "cart", but I can't seem to replicate that loop in JS.
I tried to do it with a regex expression in order to allow any number inside the first set og brackets, but it won't work (I'm quite new to JS so not sure if I did it correctly).
Does anyone have a suggestion?
UPDATE:
This was my last attempt to use regex:
var nums = /^[0-9]+$/;
function readCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
cart = readCookie("cart["+ nums +"][id]");
Please see the excellent MDN article on how to access cookies in javascript, they even provide a full implementation for reading/writing cookie values. In a nutshell, cookies can be accessed as attribute of the document: document.cookie. That attribute has all the cookies belonging to your domain stored as string (e.g.: foo=bar;baz=bizz). To access an individual element you would have to come up with some regex magic, thus the link to the MDN article. ;-)
The solution there let's you set/get/check/delete cookies very comfortable, e.g.
docCookies.setItem("foo", "bar");
docCookies.getItem("foo"); // bar
docCookies.hasItem("foo"); // true
docCookies.removeItem("foo");
Btw, if you're using jQuery, there's a very nice plugin.
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product
HI,
I am nearly there I think but am struggling to put the final bits in place.
I am trying to look up the the subdomain of a number of different envoronments and pass the subdomain as a variable to prefix a url called via an onclick event. This is all delivered through an xsl transformation.
I am just getting the domain passed to the link at present. Any tips on how to make this work or write the code in a better way greatly appreciated.
<xsl:text disable-output-escaping="yes">
<![CDATA[
<script type="text/javascript">
function enironment()
{
if (window.location.host.toLowerCase() === 'www.mydomain.com') {
SsoServer = "https://sso.mydomain.com";
}
else{
var sub_domain = window.location.split('.')[0].split('//')[1];
SsoServer = "https://" + sub_domain + "sso.mydomain.com";
}
top.location.replace(SsoServer);
}
</script>]]>
</xsl:text>
<a href="#" onClick="javascript:enironment()" title="Sign in">Sign
in</a>
Might be because you have three equals signs instead of two here:
if (window.location.host.toLowerCase() === 'www.mydomain.com') {
Should be:
if (window.location.host.toLowerCase() == 'www.mydomain.com') {
How to save div title into cookies? And how to get this saved data, back?
<script type="text/javascript">
function setcookie(title, value, exp) {
var expdate = new Date();
expdate.setDate(expdate.getDate() + exp);
document.cookie = title+'='+value+';expires='+expdate.toGMTString()+';path=/';
}
</script>
<div title="1" onclick="setcookie();"></div>
See this question about jQuery and cookies. It will be easier to use a plug-in, like http://plugins.jquery.com/project/cookie.
Use following code to get the title of the div:
title = $("div").attr("title");
You may want to look into window.localStorage. It's very effective for what you are looking to do.
//Save the data
window.localStorage['mydiv'] = $('div').attr('title');
//Retrieve the data
$('div').attr('title', window.localStorage['mydiv']);