Detect if string is part of string value of an ID value?

JavaScript and client side scripting.

Moderator: General Moderators

User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Thanks for the reply though I think I confused you more then I did myself? I'm trying to change the backgroundColor of the top header and the top divs, not the second set that is in the middle. So first it's intended to have you click on a color (#f0f for example) and then say click on the first/top header.

So what I am trying to do is assign a variable for IDs that do not start with 'color'. If an element with an ID that starts with 'color' is clicked the script I last posted should get the last three letters after 'color' which will then be assigned to the variable color.

So...

1.) Click an element you want to change (in the example code the top header or the very first three divs).
2.) Click the color you want to use as the first clicked element's new background color (the colors are the IDs that start with 'color' under the second/middle header). I need to get some sleep, I'll take a crack at this later.

Also thanks for the suggestion, I just had a lot of commented out code (I just end up copy/pasting the file and giving it a new/higher number to reserve code I'm not sure I should just erase) so I never ended up indenting anything which on a moderate sized script like this doesn't really help much.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

JAB Creations wrote:so I never ended up indenting anything which on a moderate sized script like this doesn't really help much.
Be sure it helps ;)

Coding the behaviour you want to achieve is easy - I've added 3 additional lines in my code and it works ;) So ... get some sleep and do it :)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

I just need to know how to avoid executing a script if the value isn't set and then I'll post the working code.

This isn't working...

Code: Select all

if (result==null) {return false;}
...nor is this...

Code: Select all

if (result==undefined) {return false;}
...nor is this...

Code: Select all

if (!result) {return false;}
That's it, if I can get that fixed that then I'll post the working script. Thanks! :D
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

3 lines ...

Code: Select all

// we need global variable, right?

window.onload=function()
{
        elements = document.body.getElementsByTagName('*');
        for(i=0; i < elements.length; i++)
        {
                elements[i].onclick = function()
                {
                        re = /^color([0-9abcdef]+)/i;
                        result = this.id.match(re);
                        if (result)
                        {
                                this.style.backgroundColor = result[1];
                                // what should be changed here?
                        }
                        else
                        {
                               //what should be added here?
                        }
                }
        }
} 
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

I already have the script working at my end, I just need to handle the undefined variable. Please answer my last post, then I will post what I have, and we can go from there.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

JAB Creations wrote:I already have the script working at my end ...
Post it ...
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

I'm reluctantly posting this because I easily presume everyone replying is going to ignore my question which will negate refining my effective understanding of JavaScript at this point. Designers and developers approach issues differently and it easily creates situations of communication related friction. Remember, I'm not good with concepts, to me code is best thought out as Lego bricks that I put together and take apart until something makes sense.

So please answer my question, how do I detect and avoid executing the end of the script if the variable result is not defined?

Code: Select all

window.onload=function()
{
 elements = document.body.getElementsByTagName('*');
 for(i=0; i < elements.length; i++)
 {
  elements[i].onclick = function()
  {
   re = /^color([0-9abcdef]+)/i;
   //result = this.id.match(re);
 if (this.id.match('^color'))
 {
 var mycolor = this.id;
 result =  mycolor.substr(5);
}
   if (this.id && !this.id.match('^color'))
   {
    this.style.backgroundColor = '#' + result;
   }
  }
 }
}
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

Well, even designers know what ident is ... I'm trying to help you, but you are not trying to help me helping you ...

Add

Code: Select all

result = null;
at the top of the script and check with:

Code: Select all

if (this.id && !this.id.match('^color') && result)
Also, I would recomend you to use "if/else" statements, not only "if" ;)

Almost everyone here, in this forum, would try to learn you how to do it, not to show you copy-paste example ... Even better - everyone would try to show you best practices :)
Last edited by VladSun on Mon Oct 01, 2007 8:23 pm, edited 1 time in total.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Thank you, that made sense to me. I'm learning the basics still and best practices are too complex for me at this point to figure out on my own to begin with. I was assuming that a variable with an unassigned value would automatically be null or some other zero equivalent to begin with.

How did you feel it should have been approached?

Anyway here is the code...

Code: Select all

function coloreditor() {
result = null;
 elements = document.body.getElementsByTagName('*');
 for(i=0; i < elements.length; i++)
 {
  elements[i].onclick = function()
  {
   re = /^color([0-9abcdef]+)/i;

   if (this.id.match('^color'))
   {
   var mycolor = this.id;
   result =  mycolor.substr(5);
   }

   if (result == null) {return false;}
   else if (this.id && !this.id.match('^color'))
   {
   this.style.backgroundColor = '#' + result;
   }
  }
 }
}

function start() {
 coloreditor();
} 
window.onload = start;
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

It is a good practice always to define your variables and assign values to them.

You saw the JS error message "result is undefined" ... so, it make sense to define it ;)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

That makes sense once it's presented, but I obviously wasn't coming up with the answer on my own. I was by the way never disagreeing with your statement on spacing, I just don't usually work too much in JavaScript versus XHTML and CSS.

There is a problem with this script breaking other scripts. While I could completely modularize all the JavaScript off my work and in to external JavaScript files (meaning everything including the event attributes from the XHTML elements themselves) I have left the event attributes for some obvious flexibility (why define the same event to trigger from two different IDs and then have to always add IDs to the JavaScript itself, very unnecessary).

So I'm sure this is an exceptionally rare question in JavaScript but how do we go about detecting if an attribute is defined on an element? Time to do some chores but just in case while I'm AFK I would presume it would be something simple such as...

Code: Select all

if (document.getElementById("myidhere").onclick)
Let's assume that the XHTML elements with other scripts look something like this...

Code: Select all

<element onevent="myfunction();" />
If you need a live example visit the preview site in my signature. :)

I've got some more spiffy things I want to do though I'm trying to take achieve my goals in the smallest of possible steps. :wink: Thanks for your help!
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

I've been messing about with hasAttribute for a while now and I'm hitting a couple errors. Here are the two things I've tried...

Code: Select all

   if (result == null) {return false;}
   //else if (result.hasAttribute('onclick')) {alert('this element has an onclick attribute');}
   else if (document.getElementById([result]).hasAttribute('onclick')) {alert('this element has an onclick attribute');}
The commented out part triggers an error message result.hasAttribute is not a function.

The second attempt triggers the error message document.getElementById([result]) has no properties. Same error message applies when I remove the brackets.

Suggestions?
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Ops! I was applying it in the wrong part of the script.

Now I have to figure out how to properly return so that other scripts can still execute onclick events. At the bottom of the page is a header with an onclick attribute event, clicking a color and then clicking it will not assign it a new backgroundColor. Suggestions are welcome on the return goal. :)

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Case</title>
<script type="text/javascript">
//<![CDATA[
//
// dynamic ID
function coloreditor() {
result = null;

 elements = document.body.getElementsByTagName('*');
 for(i=0; i < elements.length; i++)
 {
  elements[i].onclick = function()
  {
   re = /^color([0-9abcdef]+)/i;

   if (this.hasAttribute('onclick'))  {alert('your id has an onclick so return false'); return}
   else {if (this.id.match('^color'))
    {
    var mycolor = this.id;
    result =  mycolor.substr(5);
    }
   }

   if (result == null) {return true;}
   else if (this.id && !this.id.match('^color'))
   {
   this.style.backgroundColor = '#' + result;
   }
  }
 }
}

function start() {
 coloreditor();
} 
window.onload = start;
//]]>
</script>
<style type="text/css">
h2 {background-color: #ddd; margin: 16px 0px 0px 0px;}
div {background-color: #ccc;}
</style>
</head>

<body>

<h2>IDs below without color as ID attribute's value</h2>
<div id="ha1">#ha1</div>
<div id="hb2">#hb2</div>
<div id="hc3">#hc3</div>

<h2>ID's below contain the string 'color' in the value of their ID attribute</h2>
<div id="colorf0f"">#f0f</div>
<div id="colorf00">#f00</div>
<div id="color00f">#00f</div>

<h2>ID's below contain 'color' in string but not at the begining and <i>should</i> fail.</h2>
<div id="acolorf0f"">#f0f</div>
<div id="acolorf00">#f00</div>
<div id="acolor00f">#00f</div>

<h3 id="header3end" onclick="return true;">this header should do nothing</h3>

</body>
</html>
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Here is an updated version along with a second script that the color editor script breaks. I am guessing the color editor script is returning incorrectly (as desired) though I could also be approaching this in the wrong way...

To test the other script rename the start function to something such as s1tart, save, reload, and click on the header at the very bottom of the page. That is the desired behavior of the other script.

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Case</title>
<script type="text/javascript">
//<![CDATA[
// setStyleById: given an element id, style property and
// value, apply the style.
// args:
// i - element id
// p - property
// v - value
//
function setstylebyid(i, p, v) {
var n = document.getElementById(i);
n.style[p] = v;
}

// Color Editor
function coloreditor() {
result = null;

elements = document.body.getElementsByTagName('*');
for(i=0; i < elements.length; i++)
{
elements[i].onclick = function()
{
re = /^color([0-9abcdef]+)/i;

if (this.hasAttribute('onclick')) {alert('your id has an onclick so return false'); return}
else {if (this.id.match('^color'))
{
var mycolor = this.id;
result = mycolor.substr(5);
}
}

if (result == null) {return true;}
else if (this.id &&!this.id.match('^color'))
{
this.style.backgroundColor = '#' + result;
}
}
}
}

function start() {
coloreditor();
}
window.onload = start;
//]]>
</script>
<style type="text/css">
h2 {background-color: #ddd; margin: 16px 0px 0px 0px;}
div {background-color: #ccc;}
#prompt {
background-color: #000000;
border: #fff solid 1px;
color: #a7a68f;
display: none;
height: 398px;
left: 50%;
margin-top: -198px;
margin-left: -40%;
position: absolute;
top: 50%;
width: 80%;
z-index: 3;
}
</style>
</head>

<body>

<h2>IDs below without color as ID attribute's value</h2>
<div id="ha1">#ha1</div>
<div id="hb2">#hb2</div>
<div id="hc3">#hc3</div>

<h2>ID's below contain the string 'color' in the value of their ID attribute</h2>
<div id="colorf0f"">#f0f</div>
<div id="colorf00">#f00</div>
<div id="color00f">#00f</div>

<h2>ID's below contain 'color' in string but not at the begining and <i>should</i> fail.</h2>
<div id="acolorf0f"">#f0f</div>
<div id="acolorf00">#f00</div>
<div id="acolor00f">#00f</div>

<h3 id="header3end" onclick="setstylebyid('prompt', 'display', 'block');">this header should open a new layer onclick!</h3>

<div id="prompt">
<p>This is a layer that is supposed to be hidden by default.
Executing the script to display this layer while setting colors is our goal.</p>
</div>

</body>
</html> 
Post Reply