Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to set the attribute to an element without much success:\

Status
Not open for further replies.

Tiram

Programmer
Apr 11, 2005
11
NO
I have this JavaScript that should set the class attribute of the DIV#main to e.g. "1200pluss" or whatever, depending on window width -- but I can't get it to work! This is the script:

Code:
function getBrowserWidth()
{
    if (window.innerWidth)
    {
        return window.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth != 0)
    {
        return document.documentElement.clientWidth;
    }
    else if (document.body)
    {
        return document.body.clientWidth;
    }
    return 0;
}

function changeClass()
{
   var theWidth = getBrowserWidth();
   var theElement = document.getElementById("main");
    if ( theWidth > 1400 )
    {
        theElement.setAttribute('class','1400pluss');
    }
    else if (theWidth > 1200)
    {
        theElement.setAttribute('class','1200pluss');
    }
    else if (theWidth > 800)
    {
        alert(theElement + '  800px+');
    }
    else
    {
        theElement.setAttribute('class','fallback');
    }
    return true;
}

(Feel free to ignore the bit corresponding to "theWidth > 800" -- that's my test line:)

The script detects the width just fine, and using an alert or a doc.write works, but not "setAttribute":\

A friend suggested using this instead:

Code:
theElement.className='fallback';

... but that didn't work either.

I've put up a copy of the page in question here:


... and the script here:


... if you want to have a closer look at it.

I'd appriciate any help on the subject!
 
Your friend would be right in telling you to use the className property. Try a simple example of changing the class using this method and then apply the functionality to your existing problem.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
I tried using "className" already, and couldn't make it work. Maybe the fault is somewhere else?
 
Maybe it is then. Try doing a simple example as I suggested (so you have a working starting point) then you can slowly build the example up to do what you need it to do.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
I have changed class names with a line like this:
document.getElementById('myObj').className = 'myclass';

Your approach of theElement.className='fallback'; should work as well as long as you are actually getting the object reference in theElement.

If the object is actually retrieved without a problem then it could be something else in your code.
Try setting alerts in the same block as the statements to change the className just to ensure the logic is executing under those circumstances.


Stamp out, eliminate and abolish redundancy!
 
Good eyes manarth, I did not notice the numbers.

Tiram, the best thing to do anytime something is giving you this much trouble is to simplify.

Create a different page with only enough content to show the difference in your styles when an alternate is selected.
Include only the portions of the style sheet relevant to what you are going to display in this page and trim out all code unrelated to the test.

If you have a bug in your stylesheet it is entirely possible that your code is working but the browser is ignoring portions of the style and so you do not see the effect you expect to see. Automatically you would think the javascript failed but it does not have to be the javascript causing the problem.

Make yourself what they call a test harness which as described above contains only the essentials of what you need to test. If it fails there then you have a lot fewer possibilities you have to consider to find the source of the problem.

BTW, do you get any errors?
I glanced at your page and did not get any errors but it seems my current browser settings were not sufficient to cause a change in styles anyway.


Stamp out, eliminate and abolish redundancy!
 
I've tested with this alert rather than a statement:

Code:
alert(theElement + ' \ \ \ ' + theWidth + 'px');

... and the popup gives me this:

Code:
[Object HTMLDivElement]    1245px

(Up and working now, on the page I've linked to furter up!)

The object is correct, as far as I can tell, but it's hardly my area of expertise ... And 1245 is how many pixels I've got available, so that seems to work too.

I've tried these:

Code:
theElement.setAttribute('class','hm1400pluss');

document.getElementById('main').className = 'hm1400pluss';

theElement.className='hm1400pluss';

theElement.setAttribute('className','hm1400pluss');

Some of them seemed more feasible than others, but none of them worked:\

Neither the Opera JS console nor the Firefox one gives me any errors, BTW.

manarth: I wish I could use just CSS, that's what I'd definitively prefer. But the customer wants different % widths for different screen widths, so ...
 
here's about the most rudimentary test harness you can make:
Code:
<html>
 <head>
  <title>test</title>

  <style type="text/css">
   .foo { color:red }
   .bar { color:blue }
  </style>
 </head>

 <body>
  <div id="theDiv">i am the div</div>
  <input
   type="button"
   value="class foo"
   onclick="document.getElementById('theDiv').className = 'foo';" />
  <input
   type="button"
   value="class bar"
   onclick="document.getElementById('theDiv').className = 'bar';" />
 </body>
</html>

if this doesn't work for you, you've got some issues with your browser.

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Maybe all of this is not working because you are trying to set the class on a DIV element, but your CSS is specifically set up to only look for the class on the body element:

(from style_de.css)

Code:
body.hm1400pluss, 
body.hm1200pluss, 
body.hm1000pluss, 
body.fallback {
    color: #fc0 !important;
    text-decoration: underline !important;
    }

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
The kicker is - there's no other reference to those classes... so even if the class was set correctly - you'd never be able to tell the difference, as nothing would change.

*sigh*

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I finally got it working! Thanks Dan, for pointing out the embarassingly obvious ... *blushes*

Code:
function getBrowserWidth()
{
    if (window.innerWidth)
    {
        return window.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth != 0)
    {
        return document.documentElement.clientWidth;
    }
    else if (document.body)
    {
        return document.body.clientWidth;
    }
    return 0;
}

function changeClass()
{
   var theWidth = getBrowserWidth();
   var theElement = document.getElementById('main');
    if ( theWidth > 1200 )
    {
        theElement.className = 'hm1200pluss';
    }
    else if (theWidth > 1000)
    {
        theElement.className = 'hm1000pluss';
    }
    else if (theWidth > 800)
    {
        theElement.className = 'hm800pluss';
    }
    else
    {
        theElement.className = 'fallback';
    }
    return 0;
}

*puh* Thanks a lot, all of you:)

I'm afraid I have another, related question, though ... I realised when I went to put it live, that I can't call the function on onLoad of BODY, as there is already another function being loaded which can't be moved. Is there anyone who can tell me how I can load changeClass() as the document loads?
 
I realised when I went to put it live, that I can't call the function on onLoad of BODY, as there is already another function being loaded which can't be moved.

This is the solution I use:
Code:
addLoadEvent(changeClass);

function addLoadEvent(func) 
{
	var oldOnload = window.onload;
	window.onload = (typeof window.onload=='function') ? function(){oldOnload;func;}:func;
}

function changeClass() 
{
	[gray]// your code here[/gray]
}

---
Marcus
better questions get better answers - faq581-3339
accessible web design - zioncore.com
 
And amazingly enough, it worked for me too ;D Thanks a lot!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top