Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a html class with a Javascript function

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
}
like image 991
Simon Larsen Avatar asked Apr 08 '26 10:04

Simon Larsen


1 Answers

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.

like image 114
Jeremy Roman Avatar answered Apr 09 '26 23:04

Jeremy Roman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!