3

I'm developing a website and I'm having some trouple.. I want to define my class using a Javascript function, like so:

html code:

<script type="text/javascript" src="../js/active_menu.js"></script>
<a id="demo" class="<script>document.write(myFunction('index.php'));</script>" href="index.php">Home</a>

javascript code:

function myFunction(menu_punkt)
{
var state = 'not_active'
var a = document.URL.split("//");
a = (a[1] ? a[1] : a[0]).split("/"); 
a = a[1];

if (menu_punkt == a){
    state = 'navactive';
}
return state
}
2
  • I'm not sure... It should make the class="navactive" and then my menu button should be blue, but it doesn't happen. And it works if I just put in class="navactive" Commented Dec 21, 2012 at 17:53
  • Could you please explain what you're trying to achieve so we may better help? but from what I see it looks like you're trying to set the home link to a class based on whether or not you're on that current page? Commented Dec 21, 2012 at 17:53

3 Answers 3

2

You can't use the <script> tag inside an attribute. Probably the simplest change would be to do this:

<script type="text/javascript" src="../js/active_menu.js"></script>
<script>document.write('<a id="demo" class="' + myFunction('index.php') + '" href="index.php">Home</a>');</script>

If you want your page to be more accessible to users with JavaScript disabled, or you want to allow the DOM to continue to load without blocking on JS execution, you might consider an approach that changes the element after the fact instead.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the className property:

document.getElementById("demo").className = myFunction('index.php');

Make sure you call this after demo has been added to the DOM, else document.getElementById("demo") will fail.

Comments

0

First, remove the <script> tags from the 'class' value, you can make this much more elegant with JQuery:

$(document).ready(function() {
    $('#demo').addClass(myFunction('index.php'))
});

function myFunction(menu_punkt)
{
    var state = 'not_active'
    var a = document.URL.split("//");

http://docs.jquery.com/Tutorials:Introducing_$%28document%29.ready%28%29

*If you don't want to hardcode the name of your page in your function's argument, you can sort something out with 'window.location.href' and the 'substr' function.

http://www.w3schools.com/jsref/jsref_substr.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.