Reputation: 235
HTML
<?php $var = 1; include('PHP/NavigationBar.php'); ?>
Navigation.php
<div class="sidenav">
<h5>JavaScript</h5>
<button class="w3-button w3-theme w3-block w3-left-align w3-padding-small"
onclick="myAccFunc('1')"> Main Heading <i class="fa fa-caret-down"></i></button>
<div id="1" class="w3-blue w3-hide w3-card" >
<a class="<?php echo (($var==1)?'active':'');?>" href="Page1.php">Page 1</a>
<a class="<?php echo (($var==2)?'active':'');?>" href="Page2.php">Page 2</a>
<a class="<?php echo (($var==3)?'active':'');?>" href="Page3.php">Page 3</a>
<a class="<?php echo (($var==4)?'active':'');?>" href="Page4.php">Page 4</a>
</div>
</div>
Here is my Navigation Menu. Currently with just 4 items and the Class="Active" represents the active Page So if the user is on page 2, the page 2 on the Nav will be highlighted with that Class
This works completely fine but i have to shift from PHP to JavaScript
So the HTML Line becomes
<script type="text/javascript" src="PHP/Navigation.js"></script>
I can get the current URL by window.location.href How do i pass this to the JS File and How do i include the HTML Contents in a JS File (Currently PHP File)?
I have put all the Weblinks in an Array in the JS file. So what do i do next to achieve the same thing i achieved using PHP and HTML but with JavaScript and HTML.
I just need to Import the Nav Menu and Highlight the Current Site using JavaScript
Upvotes: 0
Views: 77
Reputation: 2321
It took me time to understand your expectations but now here is your Navigation.js
var activeClass = new Array(4);
if(window.location.href.includes('Page1.php')) {
activeClass[0] = 'active';
} else if(window.location.href.includes('Page2.php')) {
activeClass[1] = 'active';
} else if(window.location.href.includes('Page3.php')) {
activeClass[2] = 'active';
} else if(window.location.href.includes('Page4.php')) {
activeClass[3] = 'active';
}
document.write('<div class="sidenav"><h5>JavaScript</h5>'+
'<button class="w3-button w3-theme w3-block w3-left-align w3-padding-small" onclick="myAccFunc(1)">'+
' Main Heading <i class="fa fa-caret-down"></i></button><div id="1" class="w3-blue w3-hide w3-card" >');
document.write('<a class="'+activeClass[0]+'" href="Page1.php">Page 1</a>');
document.write('<a class="'+activeClass[1]+'" href="Page2.php">Page 2</a>');
document.write('<a class="'+activeClass[2]+'" href="Page3.php">Page 3</a>');
document.write('<a class="'+activeClass[3]+'" href="Page4.php">Page 4</a>');
document.write('</div></div>');
Upvotes: 2