Include HTML in JavaScript (.js) File - javascript

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

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>');

Related

active class not working on index page when index doesn't have in url

myapp
├── index.php
├── apps.php
├── contact.php
└── sidebar.php
in sidebar.php
<nav class="side-bar">
<ul>
<li>
<a href="index.php" class="category" >
<i class="fi fi-bs-home"></i>
<span>Home</span>
</a>
</li>
<li>
<a href="room.php" class="category">
<i class="fi fi-bs-apps"></i>
<span>Room</span>
</a>
</li>
<li>
<a href="contact.php" class="category">
<i class="fi fi-br-comment-alt"></i>
<span>Contact</span>
</a>
</li>
</ul>
</nav>
in index.php apps.php contact.php
#more code here
<php include('sidebar.php');
#more code here
and I use some of JavaScript to add active class on the link of my current page
Note I use active class to highlight on the link of my current page
const category = document.querySelectorAll('.category');
const activePage =windows.location.href;
category.forEach(link =>{
if(link.href === activePage){
link.classList.add('active');
}
})
Problem
Active class work normally when I link to any page like ..\myapp\index.php , But when i open ..\myapp\ It will auto open index.php that make my link tag index.php page doesn't have active class
What I want?
I want to make it active class on home Page (index.php) when I open ../myapp/ in the url
I don't know if it's that what you want, but I did something on my own project.
<?php
$filename = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
$filename = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
?>
<div class="top-nav">
<?php if($filename == 'CopyMail'){ ?>
<a class="active top-item home" href="#home">Acceuil</a>
<?php } else { ?>
<a class="top-item home" href="../reusable/pages/index.html">Acceuil</a>
<?php } ?>
<?php if($filename == 'write'){ ?>
<a class="active top-item write" href="#write">Écrire</a>
<?php } else { ?>
<a class="top-item write" href="pages/write.php">Écrire</a>
<?php } ?>
</div>
I will explain my code (I know this is note the best but it work)
the two first line get the current file you on (without the extension) and store it in a variable.
the 'if' statement compare if the current file your on (the previous you've checked) is in this code 'CopyMail', if yes it apply the class 'active' and do some other thing that you might understand. you can add as many as you want and even compare with multiple file name like: <?php if($filename == 'account' || $filename == 'register' || $filename == 'login' || $filename == 'creation') ?>
Hope this helped

Jquery code for hierarchal element is not working for a particular value in a loop

I have a sidebar drop-down menu, which is being operated using jquery, but when user clicks on the item the page refreshes and the menu collapses. To solve this,that is to keep it expanded, I decided to compare the REQUEST_URI with menu item URL, if found I will trigger the click event. To accomplish this I used the snipped
$("a[href='<?php echo $citems->url;?>']").parents("li").parents("ul.dropdown-menu").prev(".dropdown-toggle").trigger("click");
Which works for all item except for a particular item which appears at third last position in menu item list. Below is the code I am executing in which I am facing the issue:
<nav class="navbar navbar-default sidebar" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-sidebar-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1">
<ul class="nav navbar-nav asurion-sidebar" >
<?php
$nav_menu_items = wp_get_nav_menu_items( 'left-sidebar' );
$menu_items = wpse170033_nav_menu_object_tree( $nav_menu_items );
$parents = get_post_ancestors( $post->ID );
foreach($menu_items as $items)
{
$parents1 = get_post_ancestors( $items->ID );
if(count($items->children) > 0)
{
?>
<li class="dropdown first-level">
<i class="fa <?php echo $items->classes[0];?>" aria-hidden="true"></i><?php echo $items->post_title;?> <i class="fa fa-angle-down menu-arrow" aria-hidden="true"></i>
<ul class="dropdown-menu forAnimate" role="menu">
<?php
foreach($items->children as $citems)
{
if(count($citems->children) > 0)
{?>
<li class="dropdown thirdlevel ">
<a style="cursor:pointer" class="dropdown-toggle naveen" data-toggle="dropdown-submenu"><i class="fa <?php echo $citems->classes[0];?>" aria-hidden="true"></i><?php echo $citems->post_title;?><i class="fa fa-angle-down menu-arrow" aria-hidden="true"></i></a>
<ul class="dropdown-submenu forAnimate lastlevel" role="menu">
<?php
foreach($citems->children as $ccitems)
{
if(strpos($ccitems->url,'localhost')){
$sea_domain = 'localhost';
}elseif(strpos($ccitems->url,'asurion.com')){
$sea_domain = 'asurion.com';
}
$compareUrl = explode($sea_domain,$ccitems->url) ;
if($_SERVER['REQUEST_URI'] == $compareUrl[1]){
?>
<script>
$(document).ready(function(){
$("a[href='<?php echo $ccitems->url;?>']").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
<?php }
echo "<li><a target='".$ccitems->target."' href='".$ccitems->url."'>".$ccitems->post_title."</a></li>";
}
?>
</ul>
</li>
<?php
}
else
{
if(strpos($citems->url,'localhost')){
$sea_domain = 'localhost';
}elseif(strpos($citems->url,'asurion.com')){
$sea_domain = 'asurion.com';
}
$compareUrl = explode($sea_domain,$citems->url);
echo "<li><a target='".$citems->target."' href='".$citems->url."'>".$citems->post_title."</a></li>";
if($_SERVER['REQUEST_URI'] == $compareUrl[1]){
?>
<script>
$(document).ready(function(){
$("a[href='<?php echo $citems->url;?>']").parents("li").parents("ul.dropdown-menu").prev(".dropdown-toggle").trigger("click");
});
</script><?php
}
}
}
?>
</ul>
</li>
<?php
}
else
{
if(get_the_title($post->ID)=="Dashboard" && $items->post_title=="Home" && count($parents)==0)
{
echo "<li class='active'><a target='".$items->target."' href='".$items->url."'> <i class='fa ".$items->classes[0]."' aria-hidden='true'></i>".$items->post_title."</a></li>";
}
else
{
echo "<li><a target='".$items->target."' href='".$items->url."'> <i class='fa ".$items->classes[0]."' aria-hidden='true'></i>".$items->post_title."</a></li>";
}
}
}
?>
</ul>
</div>
</div>
</nav>
Any Help would be appreciated.
Here is array being iterated for sidebar menu:Array, Here in the array one of the item for which the jquery snippet is failing is under "Device" > "Phone Simulators"
This is the Extracted HTML code from Source Code (It doesnt contain js code as fiddle doesnt allow js code to be writtent in html section, to find JS code, scroll above)
I can't imagine that why you output
<script>
$(document).ready(function(){
$("a[href='<?php echo $ccitems->url;?>']").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
in a loop, it will make your HTML code looks messy. and you should not output so many $(document).ready(...) at all.
you can give your <A /> a special className like 'xxx', and output the script code before </body>.
<script>
$(document).ready(function(){
$("a.xxx").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
it's a little better.
and if you want to keep the menu's status, you should use cookie or localStorage, not by this way.
and jsfiddle want you separate your html, css, js code, but through your way, your html and js can't be separated, it's not good. you can provide some css make the jsfiddle result page looks better, it can helps someone to understand your structure.

To get value of the link using Jquery

I am trying to get value of linl which is generated from db using while loop.
When I prees on the link it should show alert window with its name.
while($trackResultRow = mysqli_fetch_assoc($trackResult)){?>
<li>
<a href="#" class="rem"
data-userid="<?php echo $trackResultRow['username']?>"
data-track="<?php echo $trackResultRow['track_name']?>">
<span class="glyphicon glyphicon-thumbs-down pull-right"></span>
</a>
<a href="<?php echo $trackResultRow['track_path']?>">
<span><?php echo $trackResultRow['username']?></span> -
<span><?php echo $trackResultRow['track_name']?></span>
</a>
<hr/>
</li>
<hr>
<?php
}
?>
And Jquery code
$(function() {
$(".rem").on("click", function(e) {
e.preventDefault();
var $link = $(this), // save for later
username = $(this).data("userid"),
track = $(this).data("track");
return alert (username);
});
});
But it does not work....Can anybody help me to fix this code?
You code is working for me, however I noticed that your two anchor tags are very close to each other. Are you adding event listener to first anchor tag and clicking on second? See example code below
$(function() {
$(".rem").on("click", function(e) {
e.preventDefault();
var $link = $(this), // save for later
username = $link.data("userid"),
track = $link.data("track");
return alert(username);
});
});
.glyphicon:after {
content: 'Icon'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ul>
<li>
<a href="#" class="rem" data-userid="USERNAME" data-track="TRACK_NAME">
<span class="glyphicon glyphicon-thumbs-down pull-right "></span>
</a>
<a href="track_path">
<span>username</span> -
<span>track_name</span>
</a>
<hr/>
</li>
<li>
<a href="#" class="rem" data-userid="USERNAME" data-track="TRACK_NAME">
<span class="glyphicon glyphicon-thumbs-down pull-right "></span>
</a> -
<a href="track_path">
<span>username</span> -
<span>track_name</span>
</a>
<hr/>
</li>
</ul>

Hide menu item according to user account

On my login mysql table, i have an account type column. If the user has a Manager account type, i want to show a management menu item and if not hide it.
This is pretty simple but its not working:
In my header, i have the following:
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>
I tried without the echo has well.
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<div class="text-bg"><span class="text-slim">Welcome,</span> <span class="text-semibold"><?php echo $_SESSION['account_type'] ?></span></div>
Have you tried using php if while rendering your menu? Something like this:
<?php if($_SESSION['account_type'] == 'Manager'): ?>
<div id="management_menu">
<ul>
<li>
Dashboard
</li>
<li>
Users
</li>
</ul>
</div>
<?php endif; ?>
Where is your javascript code in the document? If your javascript code is on the top of the document, it possibly shows or hides the <div> element properly, but, because the <div> element is at the bottom of the document, it is hidden because its "style" says so.
The solution is to move the javascript code below the <div> element, this will solve the "execution order" problem you have. Example :
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<?php
session_start();
$_SESSION['account_type'] = "Manager";
?>
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>

How to pass PHP variables to JavaScript onclick and then insert them into Bootstrap Modal

I want to create a bootstrap modal for social sharing buttons in my wordpress blog. For the modal to be visible, I have to place it outside the post (loop) but its trigger (button) inside the post. I want to pass the URL and Title of the post to the Sharing Buttons inside the modal.
I have created two variables inside the post to get its URL and title:
<?php
// Get current post URL
$URL = get_permalink();
// Get current post title
$Title = str_replace( ' ', '%20', get_the_title()); ?>
Then, I created the trigger inside the post to display the modal
<button class="btn btn-link btn-lg" id="socialbtn" data-toggle="modal" data-target="#myModal">Share</button>
And in the modal body, I have many buttons, like
<a class="ssk ssk-text ssk-facebook" href="https://www.facebook.com/sharer.php?u=***URL of the post***">Facebook</a>
<a class="ssk ssk-text ssk-twitter" href="https://twitter.com/share?url=$URL&text=$Title$" >Twitter</a>
What I want to do is to replace the $URL in href of Facebook and Twitter with the URL of the post and likewise the title.
I know that I have to use JavaScript, but I'm unable to figure out the correct syntax.
Will be thankful for help. :)
I did it like this:
In the trigger button, I set the data attributes as follows:
<button class="btn btn-link btn-lg" id="socialbtn" data-url="<?php echo $URL; ?>" data-title="<?php echo $Title; ?>">Share</button>
then got the facebook and twitter URLs in separate variables and then set the href attributes as follows:
<script>
$(document).on("click", "#socialbtn", function () {
var url = $(this).data('url');
var title = $(this).data('title');
var fburl = "https://www.facebook.com/sharer.php?u="+url;
var twurl = "https://twitter.com/share?url="+url+"&text="+title;
$("#facebook").attr("href", fburl);
$("#twitter").attr("href", twurl);
</script>
And in the modal body, used the anchor tags as follows:
<a class="ssk ssk-text ssk-facebook" id="facebook" href="#">Facebook</a>
<a class="ssk ssk-text ssk-twitter" id="twitter" href="#">Twitter</a>
You have to output them using PHP:
<a class="ssk ssk-text ssk-facebook" href="https://www.facebook.com/sharer.php?u=<?php echo $URL; ?>">Facebook</a>
<a class="ssk ssk-text ssk-twitter" href="https://twitter.com/share?url=<?php echo $URL; ?>&text=<?php echo $Title; ?>" >Twitter</a>
$(".ssk-facebook").attr("href", "YourNewURL");
$(".ssk-twitter").attr("href", "YourNewURL");
$( "#socialbtn" ).click(function() {
$(".ssk-facebook").attr("href", "https://www.facebook.com/sharer.php?u=<?= $URL ?>");
$(".ssk-twitter").attr("href", "https://twitter.com/share?url=<?= $URL ?>&text=<?= $Title ?>");
});
You have to identify which button the user have clicked on.
You can archive that by using unique IDs OR by adding hidden inputs or divs containing the correct hrefs for each post.
Then select those "href-container" relatively to the button and change the modal. ("closest(), parent(), nextAll() etc.)
Do you need code examples?
Use data attribute to add link with every post's share button:-
HTML
<!-- Share button (PLACE IT INSIDE YOUR LOOP) -->
<a data-url="<?php echo url; ?>" data-title="<?php echo $title;?>" class="open-share btn btn-primary" href="#">share</a>
<!-- Model popup (PLACE IT AFTER LOOP) -->
<div class="modal hide" id="sharepopup">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Share </h3>
</div>
<div class="modal-body">
<a id="facebook" class="ssk ssk-text ssk-facebook">Facebook</a>
<a id="twitter" class="ssk ssk-text ssk-twitter" >Twitter</a>
</div>
</div>
JS
<script>
$(document).on("click", ".open-share", function () {
var url = $(this).data('url');
var title = $(this).data('title');
$('#facebook').attr("href", "http://facebook.com?share="+url);
$('#facebook').attr("title", "http://twitter.com?share"+title);
$('#twitter').attr("href", url);
$('#twitter').attr("title", title);
// Initialize popup with Javascript.
$('#sharepopup').modal('show');
});
</script>

Categories

Resources