PDA

View Full Version : Resolved How can I add toggle functionality



james438
01-31-2011, 06:40 PM
Continuing from this thread (http://www.dynamicdrive.com/forums/showthread.php?t=60542), how can I add toggle functionality individually to these functions which changes a background color and font family respectively. Supposedly this is easy to do, but I have not had much success.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
function Color(id,col){
document.getElementById(id).style.backgroundColor=col;
}
function FontFamily(id,col){
document.getElementById(id).style.fontFamily=col;
}
</script>
</head>

<body>
<a onclick="Color('d1','red');">Anchor</a><br>
<a onclick="FontFamily('font','Arial');">Font Family</a>
<div id="font" style='font-family:verdana;'>This is a test of the Emergency Broadcasting System. This is only a test.</div>
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div>

</body>

</html>

djr33
01-31-2011, 07:56 PM
What is "toggle functionality"?

(By the way, sorry if I interrupted the previous thread.)

Beverleyh
01-31-2011, 08:33 PM
I can show you a jQuery example (in the morning when I'm not stuck on my phone) but hopefully Vic or one of the other javascript guys will be able to help you expand your current/normal javascript code in the meantime.

ajfmrf
01-31-2011, 09:48 PM
http://webhost.bridgew.edu/etribou/layouts/comic/index.html

You can change font size,background color, and I think the type of font also.

Bud

james438
01-31-2011, 11:33 PM
djr33, I am starting a new topic as the old one was resolved like you said. When I make links I like to make them bold and blue so that people can easily find them. I added the link just in case someone might find it useful. Maybe not though. Toggle functionality is where you click a link or button and it will switch from one set of instructions to another and back again. It usually is defined as an on off switch.

Beverly, thanks, that would be helpful and good to try out. Since I am very new to javascript I am going to try and learn some of the basics first.

ajfmrf, that was a pretty cool link. Strictly speaking that is not quite the definition of toggle though. Very cool, though, and I would very much like to do something like that at some point soon.


Toggle: To alternate between two or more electronic, mechanical, or computer-related options, usually by the operation of a single switch or keystroke.

djr33
02-01-2011, 12:41 AM
You have all the components needed to create a "toggle" function except the alternation and, more importantly, a way to check if something is currently "on" or "off".

Here's a basic version in pseudo-JS:

function toggle(arguments) {
if (is_it_on) {
turn_it(off);
}
else {
turn_it(on);
}
}

Now the question is about these three arbitrary terms I've used: is_it_on, turn_it(off), and turn_it(on).

You already know function (turn_it()) for the last two in JS, or at least you can easily construct them from what you have. The if/else handles the alternation.

The remaining questions are:
1. How do we define "it"-- this needs to be based on an element on your page and some property.
2. How do we define "on" and "off"-- these will be values for that property. They might be "blue" and "red" or "none" and "block" (for displaying a div).
3. (most important) How do we handle is_it_on?

From those, we need two things:
1. A way to store the "on"/"off" value.
2. A list of values.

Let's look at (2) first:
A list in programming is usually an array. You can use an array for this if you want, though for just a binary distinction it may be simpler to write it out as the if/else above. This means hard-coding the values into the function. Or you could leave them as variables and have a function definition like this:
function toggle(element,onvalue,offvalue) {....
The last two arguments are the values it will use, the first if it's "on", and the second if it's "off"-- you can think of these as if/else too.

As a tangent if you did use the array method, you wouldn't use if/else in that way. You'd check the current value (not "on"/"off", but an array key) and add one to that key and set that value; if that value happens to be greater than the number of items in the array, set it back to 0.


Now, time to work out part (1) above, how to determine if it is on or off.
This relates to how you store the values. If they are hard coded, then it's easy to check if the element currently has a property. For example, if element.style.backgroundColor is blue, then make it red; if not, make it blue.
If you don't want to hard code these values, you could check against a variable.

Or, you could approach this in a completely different way (probably required if you use the array method described above):
Store a variable that "remembers" whether it is on or off. (If no value yet, assume off.) So just check if this variable is "on" and if so you can change BOTH the value to the "off" setting and the variable to "off" to remember this; repeat.

The most common way of doing toggles like this is to use a checkbox; this provides a built-in method of checking if something is on or off-- just check to see if the checkbox is checked or not.


I hope the explanation helps, but if you're looking for the code specifically then let me know the details from above and I can write an example. None of this requires advanced Javascript coding, since you already know the basic ways to access the properties you are using-- whether you're using it in an if or to set it, the way to access the background color is the same. (And that applies to most if not all html/css properties you can access via Javascript.)



As a convenient shorthand, you could also use the shorter version here, which is equivalent to the code at the start of the post:

function toggle(arguments) {
turn_it (is_it_on?off:on);
}

And you can if you'd like do this directly in the onclick event:
<a href="#" onclick="return setbackgroundcolor(this.style.backgroundColor=='blue'?'red':'blue');">...</a>
(Note that I used a specific function name here because I'm talking about a specific property as an example.)

Of course your specific page/goals will determine how you should set this up, either inline or in the function definition.

james438
02-01-2011, 01:40 AM
I'll try and work with what you have described, but my understanding of javascript is limited entirely to the script I posted above, so syntax and function names are a bit lost to me, so an example would be very helpful. For example, I am not sure when I see a sample script whether the word is a user defined function or a built in function.

So far, he only functions that I know are built in functions are: function, if, else, and write.

djr33
02-01-2011, 03:10 AM
I am not much beyond you in using Javascript, but it's generally similar to PHP in creating functions. The syntax is like what I posted above. Just try it and then post it here so we can work out the bugs.

james438
02-01-2011, 03:13 AM
heh, it'll be a learning experience for both of us then ;)

james438
02-01-2011, 07:04 AM
got it


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript">
function Color(id,col){
document.getElementById(id).style.backgroundColor=col;
}

function FontFamily(){
var col=document.getElementById('a1').style.fontFamily;
if (col=="\"verdana\"")
{document.getElementById('a1').style.fontFamily="arial";}
else {document.getElementById('a1').style.fontFamily="verdana";}
}
</script>
</head><body>
<a onclick="Color('d1','red');">Anchor</a><br>
<a onclick="FontFamily();">Font Family</a>
<div id="a1" style='font-family:verdana;'>This is a test of the Emergency Broadcasting System. This is only a test.</div>
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div>
</body></html>

ok, in this code we have two functions. In the first function, Color, we have two values, id and col that are being retrieved from this line <a onclick="Color('d1','red');">Anchor</a><br> with id being d1 and col being red. When the anchor is clicked the two values are placed into the function and processed.

From what I can tell, in
document.getElementById(id).style.backgroundColor=col;document is the entire document that contains the id of "d1", which in this case is
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div> getElementById(id) is the element that is between the div tags. style is
width:200px;height:200px;background-color:blue; and style.backgroundColor is blue. the background-color is recognized by removing the dash and changing the letter right after the dash to a capital letter.

The value of various aspects of the element can be altered with commands like
document.getElementById(id).style.backgroundColor=colwhere col is and always will be "red" as is defined by <a onclick="Color('d1','red');">

Once the function runs the values for id and col are lost. I do not want the values to be lost, so in the second function I define the variable with the value of an item that is in the element. In this case I use the value retrieved from the element (a1), which is font-family, which has the value of verdana.

now that "col" has been given the value of "verdana" I say if col="\"verdana\"" change it to arial, else change it to verdana. Now that the value of the item in the element has been changed when I run the function again the value of col will be different.

I do not know why I have to escape the quotes though.

I hope the above makes sense. I may edit this later to make sure the wording is correct.

james438
02-01-2011, 07:48 AM
sigh, except for the fact that, so far, this only works in Opera.

edit:

yuck, I think I found out the reason and it is pretty dumb. the value of cssText in

IE8: "FONT-FAMILY: verdana"
Opera: "font-family:verdana;"
Firefox: "font-family: verdana;"

If you look closely you will see that all 3 have different values. in IE8 the case is changed from the original, a space is added, and the semicolon is removed. In Opera the value is given as is. In Firefox a space is added.

Beverleyh
02-01-2011, 08:49 AM
This is the jQuery option;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

$('#color-toggle').toggle(
function()
{
$('#d1').css({'background':'red'});
},
function()
{
$('#d1').css({'background':'blue'});
});

$('#font-toggle').toggle(
function()
{
$('#a1').css({'font-family':'arial'});
},
function()
{
$('#a1').css({'font-family':'verdana'});
});

});
</script>

</head>
<body>

<a id="color-toggle">Anchor</a><br>
<a id="font-toggle">Font Family</a>
<div id="a1" style='font-family:verdana;'>This is a test of the Emergency Broadcasting System. This is only a test.</div>
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div>

</body>
</html>

james438
02-01-2011, 08:53 AM
ok, one more post and then I need to go to bed.

Most of the help I got came from http://www.plus2net.com/javascript_tutorial/string-concat.php which demonstrated some of the various string functions available in javascript.

I made several variable manipulations to come up with the following, which does work in all browsers:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript">
function Color(id,col){
document.getElementById(id).style.backgroundColor=col;
}

function FontFamily(){
var col=document.getElementById('a1').style.cssText;
var col = col.toUpperCase();
col=col.replace(": ", ":");
var end=col.substring(col.length-1,col.length);
if (end!=";") {end=";";
var col=col+end;
}
if (col=="FONT-FAMILY:VERDANA;"){
col="font-family:arial;";
document.getElementById('a1').style.cssText=col;}
else {col="FONT-FAMILY:VERDANA;";
document.getElementById('a1').style.cssText=col;}

}
</script>
</head><body>
<a onclick="Color('d1','red');">Anchor</a><br>
<a onclick="FontFamily();">Font Family</a>
<div id="a1" style='font-family:verdana;'>This is a test of the Emergency Broadcasting System. This is only a test.</div>
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div>
</body></html>

I'll probably change it a little more later, just so that it looks nice to me. The altered text has been highlighted. I feel like I was successful in learning a fair amount of javascript today.

james438
02-01-2011, 08:37 PM
Thanks Beverly, I just tried your script and it works great.

james438
02-03-2011, 03:11 AM
Here is an updated version of the script I posted earlier and originated from vwphillips:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript">
function Color(id,col){
document.getElementById(id).style.backgroundColor=col;
}

function FontFamily(){
var col=document.getElementById('a1').style.cssText;
var col = col.toLowerCase();
col=col.replace(" ", "");
var end=col.substring(col.length-1,col.length);
if (end!=";") end=";";
var col=col+end;
var needle=col.match(/font-family:(.*?);/i);
if (needle[1]=="verdana"){
col=col.replace("verdana","arial");}
else {col=col.replace("arial","verdana");}
document.getElementById('a1').style.cssText=col;
}
</script>
</head><body>
<a onclick="Color('d1','red');">Anchor</a><br>
<a onclick="FontFamily();">Font Family</a>
<div id="a1" style='font-family:verdana;color:red;'>This is a test of the Emergency Broadcasting System. This is only a test.</div>
<div id="d1" style="width:200px;height:200px;background-color:blue;" ></div>
</body></html>

The code has been refined a bit and makes use of variable manipulation, arrays, and regular expressions. As I look into javascript more I can see the high number of similarities between javascript and php. The most notable changes have been highlighted.

Beverly, after thinking it over I think I am going to work with getting my hands dirty with the javascript code as opposed to jQuery, which is cleaner, but I prefer working with the language itself. This will also help me to get a better understanding of the mechanics of javascript and I suspect this will help to keep the file sizes down.