PDA

View Full Version : Resolved changing the color of all links in a div



james438
02-16-2011, 05:14 AM
I am rather stumped on this one. I am trying to create a script where when I clink on the word red all of the links in a particular div will change to red. I seem to be doing fine with altering the text color of regular text or background colors, but with specific anchor links I am only able to change the first link using


document.GetElementById(id).style.color=color;

I know that id is supposed to only be used for one element as a unique identifier, but it is the only thing that marginally works.

coothead
02-16-2011, 10:53 AM
Hi there james438,

have a look at this example, it may suit your requirements...


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">

<title>black to red, red to black</title>

<style type="text/css">
#color {
width:100px;
padding:5px;
border:3px double #999;
text-align:center;
cursor:pointer;
background-color:#f0f0f0;
}
#lorem {
width:740px;
padding:20px;
border:1px solid #999;
margin:10px auto 0;
}
.hidden {
display:none;
}
.black {
color:#000;
}
.red {
color:red;
}
</style>

<script type="text/javascript">

function init(){

var a=document.getElementById('lorem').getElementsByTagName('a');
var obj=document.getElementById('color');

obj.className='';

obj.onclick=function() {
for(var c=0;c<a.length;c++) {
a[c].className=='red'?
(a[c].className='black',obj.firstChild.nodeValue='red'):
(a[c].className='red',obj.firstChild.nodeValue='black');
}
}
}

window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);

</script>

</head>
<body>

<div id="color" class="hidden">red</div>

<p id="lorem">
Lorem ipsum dolor sit amet, consectetuer <a class="black" href="#">adipiscing</a> elit. Cras volutpat, purus ac
pellentesque adipiscing, <a class="black" href="#">mauris</a> ligula convallis metus, vitae scelerisque nibh
orci quis mi. Cum sociis natoque <a class="black" href="#">penatibus</a> et magnis dis parturient montes,
nascetur ridiculus mus. Curabitur porttitor aliquam libero. Quisque <a class="black" href="#">molestie</a> ornare
sem. Nam euismod sem lacinia ipsum. In pharetra metus ut dolor cursus aliquam.
Maecenas eu ante quis enim <a class="black" href="#">tincidunt</a> laoreet. Pellentesque varius nunc in ipsum
pulvinar sollicitudin. Nunc et mi. Donec auctor dignissim orci. <a class="black" href="#">Aliquam</a> sed magna.
Pellentesque in dui. In <a class="black" href="#">eget</a>. elit. Praesent eu lorem.
</p>

</body>
</html>


I forgot to allow for those with javascript disabled, so made a minor modification to the code. ;)

coothead

james438
02-16-2011, 11:59 AM
Much appreciated, thanks. I am rather new to javascript, but feel better this time around about diving into the language. I am pretty sure this is exactly what I need, but I am going to need to study it a little more later later on this afternoon.

james438
02-17-2011, 05:16 AM
Hi, could you explain these lines?


for(var c=0;c<a.length;c++) {
a[c].className=='red'?
(a[c].className='black',obj.firstChild.nodeValue='red'):
(a[c].className='red',obj.firstChild.nodeValue='black');
}
The part that I a bit lost on is the highlighted section. The way I see it a.length is the number of anchors that were found in the div. If the class name is black then change it to red and vice versa. What does the ? and the colon do? Also, is it necessary that the 3 lines are separated by newlines? Is there a place where I can read about the question mark and colon?

coothead
02-17-2011, 10:08 AM
Hi there james438,

The part that I am a bit lost on is the highlighted section
Those three lines constitute a ternary operator.

The way I see it a.length is the number of anchors that were found in the div.
If the class name is black then change it to red and vice versa.
That is correct.

What does the ? and the colon do?
A very good explanation of the ternary operator can be found here...
http://www.mredkj.com/tutorials/reference_js_ternary.html

Is it necessary that the 3 lines are separated by newlines?
No, the ternary operator can be placed on one line. I placed it on three lines for easier readability.
You probably noticed the other ternary operator in the script...


window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);

...which is used to remove javascript event handlers from the markup, such as...


<body onload="init()">

<div onclick="dosomething()">

<img onmouseover="swapit()" ......>



Further reading:-
http://www.quirksmode.org/js/events_advanced.html
I hope that this helps. ;)

coothead

james438
02-17-2011, 10:50 PM
Thanks for the clarification. I have been having a bit of difficulty finding official or thorough documentation for javascript unlike http://php.net or http://dev.mysql.com/doc/refman/5.5/en/index.html

molendijk
02-17-2011, 10:56 PM
Hello coothead,
Nice code.
One small remark. Your code for changing the color is FIXED in the script (nodeValue='black', nodeValue='red'). Wouldn't it be better to put a variable name in the script for the color, and then let something inside 'onclick=...' (in the body) determine what color we eventually want to produce? Something like this, for instance:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">

<title>black to red, red to black</title>

<style type="text/css">
.color{color: black}
</style>

<script type="text/javascript">

function change_style(tag,className,color) {
var els = document.getElementsByTagName(tag)
for (i=0;i<els.length; i++) {
if (els.item(i).className == className){
els.item(i).style.color=color;


}
}
}
</script>

</head>
<body><div>


<div style="display: inline; cursor: pointer; border: 1px solid black;padding:5px; background:#dedede" onclick="change_style('a','color','red')">red</div>
<div style="display: inline; cursor: pointer; border: 1px solid black;padding:5px; background:#dedede" onclick="change_style('a','color','black')">black</div>

<br><br><div >
Lorem ipsum dolor sit amet, consectetuer <a href="javascript: void(0)" class="color">adipiscing</a> elit. Cras volutpat, purus ac
pellentesque adipiscing, <a href="javascript: void(0)" class="color">mauris</a> ligula convallis metus, vitae scelerisque nibh
orci quis mi. Cum sociis natoque <a href="javascript: void(0)" class="color">penatibus</a> et magnis dis parturient montes,
nascetur ridiculus mus. Curabitur porttitor aliquam libero. Quisque <a href="javascript: void(0)" class="color">molestie</a> ornare
sem. Nam euismod sem lacinia ipsum. In pharetra metus ut dolor cursus aliquam.
Maecenas eu ante quis enim <a href="javascript: void(0)" class="color">tincidunt</a> laoreet. Pellentesque varius nunc in ipsum
pulvinar sollicitudin. Nunc et mi. Donec auctor dignissim orci. <a href="javascript: void(0)" class="color">Aliquam</a> sed magna.
Pellentesque in dui. In <a href="javascript: void(0)" class="color">eget</a>. elit. Praesent eu lorem.
</div>

</div></body>
</html>
===
Arie Molendijk.

coothead
02-17-2011, 11:15 PM
Hi there molendijk,

Wouldn't it be better to put..............
I don't know, but bearing in mind that your question is purely subjective, I believe that
one should just code in the manner that best suits his present ability and temperament. ;)

Removing presentation from content really seems to please me just now. :D

coothead

molendijk
02-18-2011, 12:25 AM
Hi there molendijk,
I don't know, but bearing in mind that your question is purely subjective, I believe that one should just code in the manner that best suits his present ability and temperament.
No, that's not what I ment. I ment that each time we want to change colors (using your script), we would have to write a new script, right? That's not a question of temperament, but of objective (lack of) economy.
===
:)Arie.

james438
02-18-2011, 02:59 AM
I shall be studying the script a bit more soon, but the other javascript I have in my page allows me to dynamically change the background color of the page, the article background color, and the article text color by first clicking on the title text and then the color chart. The javascript involved is about as long as the javascript that coothead posted and looks similar to yours molendijk. As I am quite new to javascript I wanted to keep things as simple as possible though and you may notice I still had a question or two about how it worked. It is a good suggestion though.

coothead
02-18-2011, 10:54 AM
Hi there molendijk,

certain articles that I have read suggest the separation of presentation from content.

For me, this means that coding like this...


<div style="display: inline; cursor: pointer; border: 1px solid black;
padding:5px; background:#dedede"
onclick="change_style('a','color','red')">red</div>

<div style="display: inline; cursor: pointer; border: 1px solid black;
padding:5px; background:#dedede"
onclick="change_style('a','color','black')">black</div>

...and this...


<a href="javascript: void(0)" class="color">adipiscing</a>

<a href="javascript: void(0)" class="color">mauris</a>

...should be avoided.

But please do not think that I am criticizing you for using it.
You are free to code in the manner that best suits your present ability and temperament. ;)

The code that I wrote for james438 was as specified.

If he had requested variable colors for the the links I would have coded for it. ;)
It certainly does not mean that...

...we would have to write a new script, right?

Check out the attachment to see how I would have coded the page for editable colors.

coothead

molendijk
02-18-2011, 12:39 PM
Hi there molendijk,

certain articles that I have read suggest the separation of presentation from content.

For me, this means that coding like this...


<div style="display: inline; cursor: pointer; border: 1px solid black;
padding:5px; background:#dedede"
onclick="change_style('a','color','red')">red</div>

<div style="display: inline; cursor: pointer; border: 1px solid black;
padding:5px; background:#dedede"
onclick="change_style('a','color','black')">black</div>

...and this...


<a href="javascript: void(0)" class="color">adipiscing</a>

<a href="javascript: void(0)" class="color">mauris</a>

...should be avoided.

I agree as far as the css is concerned. I didn't use stylesheets because I was afraid this would obscure things for james438.
I don't agree for the javascript. I use href="javascript: void(0)" instead of href="#" whenever I don't want the click event to bring me to a new page. href="#" will always do that, even if it does not specify a new page.



But please do not think that I am criticizing you for using it.
You are free to code in the manner that best suits your present ability and temperament. ;)
But you are free to criticize me whenever you want. That keeps us vivid.



The code that I wrote for james438 was as specified.
If he had requested variable colors for the the links I would have coded for it. ... Check out the attachment to see how I would have coded the page for editable colors.
I still don't think you have variable colors in your script, since it has:

function init(){

/********************* edit the value to suit your requirements ********************/

var colorOne='black'; /* this word should match the CSS .colorOne value */
var colorTwo='red'; /* this word should match the CSS .colorTwo value */

/***********************************************************************************/
In my script, the colors are brought in dynamically, via the onclick.
===
Arie.

coothead
02-18-2011, 01:38 PM
Hi there molendijk,

this...


function init(){

/********************* edit the value to suit your requirements ********************/

var colorOne='black'; /* this word should match the CSS .colorOne value */
var colorTwo='red'; /* this word should match the CSS .colorTwo value */

/***********************************************************************************/

...does not set the the link colors, it sets the text for the onclick event . ;)

The colors of the links are set in the CSS file...


.colorOne {
color:#000; /* this color should match the word of the javascript var colorOne */
}
.colorTwo {
color:#f00; /* this color should match the word of the javascript var colorTwo */
}

...and the onclick event swaps these classes.

If the colors for the links were to be purple and green for example, then we would have this...


function init(){

/********************* edit the value to suit your requirements ********************/

var colorOne='purple'; /* this word should match the CSS .colorOne value */
var colorTwo='green'; /* this word should match the CSS .colorTwo value */

/***********************************************************************************/

...in the javascript file and this...


.colorOne {
color:#800080; /* this color should match the word of the javascript var colorOne */
}
.colorTwo {
color:#008000; /* this color should match the word of the javascript var colorTwo */
}

...in the css file.

As for...


<a href="javascript: void(0)".....

...our friend james438 did not state that the links were empty.

If he had I would have suggested the use of the span element instead of the a element.

If he had insisted on empty links, then I would have added return false to the script. ...


obj.onclick=function() {
for(var c=0;c<a.length;c++) {
a[c].className=='colorOne'?
(a[c].className='colorTwo',obj.firstChild.nodeValue=colorOne):
(a[c].className='colorOne',obj.firstChild.nodeValue=colorTwo);

a[c].onclick=function() {
return false;
}
}
}

...leaving me with my perfectly clean markup. :D

coothead

molendijk
02-18-2011, 01:52 PM
I see. But then the colors are fixed in the css. I wanted them dynamic and completely out of the .js and .css.
As for the href, your proposition is OK. The thing is that sometimes I run into problems doing it your way (but I don't remember exactly the cases in which this occurs).
===
Arie.

coothead
02-18-2011, 02:07 PM
Hi there molendijk,

But then the colors are fixed in the css. I wanted them dynamic and completely out of the .js and .css.

That is all very well if there is only one page. ;)
You make two changes to your html and I make four changes, two to the javascript and two to the css.

But what happens if there are a hundred similar pages? :eek:

Well, I make four changes, two to the javascript and two to the css and you......:D

coothead

molendijk
02-18-2011, 02:30 PM
But what happens if there are a hundred similar pages? :eek:

Yeah, it all depends on what we want to accomplish in the end. If there were a hundred of similar pages, I would fix (as you do) the colors in the css and/or js.
But what if we had hundreds of pages containing each numerous divs in which we would not just want to toggle between red and black but, depending on the id of the divs, between all sorts of colors. I would produce the colors in the html. And you? How many scripts/css?
===
Arie.

coothead
02-18-2011, 10:30 PM
Hi there molendijk,

I would produce the colors in the html. And you? How many scripts/css?

I would, as always, keep my HTML in pristine condition. :cool:
And me, I would set the colors in the CSS. :)
one javascript and one css file. ;)

Check out the revised version to see multi-swapping colors in action. :D

coothead

james438
02-22-2011, 07:22 AM
In the original script that you posted how does this line work?

obj.onclick=function() {
It looks like a function is embedded within a function, but almost none of it makes sense. obj is a variable. I do not know what .onclick is. Is function the name of a function? and how is it being called if it is within a function?

coothead
02-22-2011, 11:32 AM
Hi there james438,



<script type="text/javascript">

function init(){

var a=document.getElementById('lorem').getElementsByTagName('a'); /* see note 2. */
var obj=document.getElementById('color'); /* see note 3. */

obj.className=''; /* see note 4. */

obj.onclick=function() { /* see note 5. */
for(var c=0;c<a.length;c++) { /* see note 6. */
a[c].className=='red'? /* see note 7. */
(a[c].className='black',obj.firstChild.nodeValue='red'): /* see note 8. */
(a[c].className='red',obj.firstChild.nodeValue='black'); /* see note 9. */
}
}
}

window.addEventListener? /* see note 1. */
window.addEventListener('load',init,false): /* see note 1. */
window.attachEvent('onload',init); /* see note 1. */

</script>


Notes:-

these three lines call function init() when the page has loaded.
&#160;
var a is the array of all the a elements within <p id="lorem">.
&#160;
var obj refers to <div id="color" class="hidden">red</div>
&#160;
obj.className=''; changes <div id="color" class="hidden">red</div> to <div id="color" class="">red</div>,
which has the effect of making it display in the page.
&#160;
obj.onclick=function() is equivalent to <div id="color" onclick="dosomething()"> without the
need for a function name.
&#160;
for(var c=0;c<a.length;c++) loops through all <a class="black" href="#"> elements within <p id="lorem">.
&#160;
a[c].className=='red' checks the className of each a element within <p id="lorem">.
&#160;
if a[c].className=='red' then it sets <a class="black" href="#"> and <div id="color" class="">red</div>.
&#160;
if a[c].className=='black' then it sets <a class="red" href="#"> and <div id="color" class="">black</div>.

I hope that this helps. ;)

coothead

james438
02-22-2011, 11:48 PM
Yes, that is helpful. I look at what you wrote for a while till it made sense, because this is rather new to me, but what you wrote helped clarify a few things.