Add class based on dynamical url parameter (click and load) - javascript

I have a php script that allows me to dynamically load content on my page based on the url paramter. Also, I have .htaccess set up so the query string prefix is hidden, meaning they look like example.com/games/demons-souls/[?page=]mods.
[?page=] is hidden via .htaccess. So far, so good.
<?php
if (!empty($_GET["page"])
&& preg_match("/^[a-z]+$/i", $_GET["page"]) == 1
&& file_exists($pageFile = __DIR__ . "/subpages/" . $_GET["page"] . ".php")) {
include $pageFile;
}
else {
include __DIR__ . "/subpages/game.php";
}
?>
Now I wanted to show which page is active in a tabpanel, where the active tab is let’s say black. So I’d need to activate the class tab.current. And to do this I need to somehow make my code recognize which url paramter is loaded and dynamically add the .current class to the appropriate tab. I hope I could explain it well enough.
I haven’t got the slightest idea how to accomplish this.
Please help.
Edit 1: Here’s an image of what I’d like to achieve:
Edit 2: As requested here’s the HTML code:
<nav id="tabs">
<a class="tab" href="game">Spiel</a>
<a class="tab" href="releases">Releases</a>
<a class="tab" href="merchandise">Merchandise</a>
<a class="tab" href="guides">Guides</a>
<a class="tab" href="emulation">Emulation</a>
<a class="tab" href="mods">Mods</a>
<a class="tab" href="savegame">Savegame</a>
</nav>

I'm not sure if this is what you are looking for but you can try the following code:
This is code should run at the top, before your nav links.
$url = htmlspecialchars($_SERVER['REQUEST_URI'],ENT_QUOTES,'UTF-8'); //this will give you something like: 'localhost/games/demons-souls/savegame'
$urlParts = explode('/',$url); //then separate string into an array by the forwardslash
$current = $urlParts[count($urlParts)-1]; //this line gets you the current page... in this case will be 'savegame'
The next step should be applied to your nav links:
<nav id="tabs">
<a class="tab <?= $current == 'game' ? 'current' : ''; ?>" href="game">Spiel</a>
<a class="tab <?= $current == 'releases' ? 'current' : ''; ?>" href="releases">Releases</a>
<a class="tab <?= $current == 'merchandise' ? 'current' : ''; ?>" href="merchandise">Merchandise</a>
<a class="tab <?= $current == 'guides' ? 'current' : ''; ?>" href="guides">Guides</a>
<a class="tab <?= $current == 'emulation' ? 'current' : ''; ?>" href="emulation">Emulation</a>
<a class="tab <?= $current == 'mods' ? 'current' : ''; ?>" href="mods">Mods</a>
<a class="tab <?= $current == 'savegame' ? 'current' : ''; ?>" href="savegame">Savegame</a>
</nav>
Here's what happens in the past code. I used ternary operator to check the name of the $url variable and if it match the href value a .current class will be added.
Or try use the JS hack.
After getting your $current in PHP have an HTML input like this:
<input id="url_value" type="hidden" value="<?= $current; ?>"/>
The input above will have the value of $current and therefore this value can be used in JS to match the href value and give that anchor tag a class of .current like this:
//the following code will be a JS code
var urlValue = document.getElementById('url_value').value; //here we get the `$current` value from our hidden input box above.
document.querySelector('a[href="'+urlValue+'"]').classList.add('current') //this gets the `<a></a>` tag that has the value of `$current`
In my opinion this JS method is more of a hack but it totally works and it removes all those PHP lines in every link in your nav.
Give it a try and let me know if this solves your problem.

#Relcode's code for generating the links can be shortened and simplified by putting link data in an array and iterating through it:
<nav id="tabs">
<?php
foreach (
[
'game' => 'Spiel',
'releases' => 'Releases',
'merchandise' => 'Merchandise',
'guides' => 'Guides',
'emulation' => 'Emulation',
'mods' => 'Mods',
'savegame' => 'Savegame',
] as $key => $description
) {
?>
<a class="tab<?php if ($current == $key ) { ?> current<?php } ?>" href="<?= $key ?>"><?= $description ?></a>
<?php
}
?>
</nav>

Related

Results in words with space don't show in php gallery

I'm creating a gallery in php, where it has a filter divided into categories. But when a word has a space it doesn't show the associated images.
I'm working on two tables, one that creates the categories and the other that is from the gallery.
This is my code and the sql queries:
Querys:
$sql = "selec categoria AS categoria_formatted from cat_lar";
$galerialar = $connect->query($sql);
$sql = "select foto,categoria_lar from galeria_lar,cat_lar Where categoria_lar=categoria";
$galerialarconde = $connect->query($sql);
Code:
<div class="popular page_section">
<div class="container">
<div class="row">
<div align="center">
<button class="filter-button" data-filter="all">All</button>
<?php mysqli_data_seek($galerialar, 0);
while( $galerialarc = $galerialar -> fetch_assoc()){ ?>
<button class="filter-button" data-filter="<?php echo $galerialarc['categoria_formatted']?>"><?php echo $galerialarc['categoria_formatted']?></button>
<?php } ?>
</div>
<br/>
<?php
while( $galerialarc = $galerialarconde -> fetch_assoc()){ ?>
<div class="gallery_product col-sm-3 col-xs-6 filter <?php echo $galerialarc['categoria_lar']?>">
<a class="fancybox" rel="ligthbox" href="admin/galeria/uploads/<?php echo $galerialarc['foto']?>">
<img class="img-responsive" alt="" src="admin/galeria/uploads/<?php echo $galerialarc['foto']?>" width="150px" />
</a>
</div>
<?php }?>
</div>
</div>
</div>
SCRIPT:
<script>
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
$('.filter').show('1000');
}
else
{
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
});
});
/* end gallery */
$(document).ready(function(){
$(".fancybox").fancybox({
openEffect: "none",
closeEffect: "none"
});
});
</script>
Can they help me? Because I've already tried to put the words with "_" and replace and it remained the same
As you suggest yourself, the image URLs can't contain whitespaces. If you already tried to replace whitespaces with underscores (_) , remember to upload the image files with that name and replace the foto url in the database with the new images.
If it doesn't work, try to investigate where exactly the problem occurs. Is the queries returning the right results (try to var_dump() the result and see if they are missing. If you think the problem happends in the HTML, try using your "inspect" feature in your browser and see if a source URL is provided for the image element and check if this URL really has an image.

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

Unable to change the active pagination button as it refreshes using php

I am trying to change the active pagination button when I click on it but it refreshes and remains the same as I get data after refresh. Here is the code:
<?php
for ($page=1;$page<=$number_of_pages;$page++) {
?>
<li class="page-item"><a class="page-link" href="view_videos.php?page=<?php echo $page;?>"><?php echo $page; ?></a></li>
<?php
}
?>
I will be getting urls as:
domain.com/hello.php?page=1
domain.com/hello.php?page=2
When I click on the second button the url changes to domain.com/hello.php?page=2 then I want change the background of second button color as active but due to page refresh its not becoming active.
Here is a screenshot of my navigation bar
Very simple:
Get the page_id like this:
$page_id = isset($_GET['page']) ? $_GET['page'] : false;
Now you have the number of the current page you are on
Then inside the loop, you could do another check like this:
<li class="page-item<?php echo ($page_id == $page) ? ' my-background' : '' ?>"><a class="page-link" href="view_videos.php?page=<?php echo $page;?>"><?php echo $page; ?></a></li>
Then you could do this in your .css-file:
.my-background {
background-color: #FF0000; /* Maybe add "!important" if necessary */
}
You have to get the page number from the URL after the page loads, and check it against each page indicator to see if it is the active one. Then you can add a class active, and style that in your CSS.
So you can try this:
<?php
for ($page = 1; $page <= $number_of_pages; $page++) {
if ($page === $_GET["page"]) {
$active = " active";
} else {
$active = "";
}
?>
<li class="page-item">
<a class="page-link <?= $active ?>" href="view_videos.php?page=<?= $page ?>"><?= $page ?></a>
</li>
<?php
}
?>
Note: <?= $foo ?> is the same as <?php echo $foo ?> manual

how to make a dynamic sidebar active on a clicking

I'm creating dynamic menu. I wanted to highlight the menu once it is selected.
We use php. just need to figure out how to append the class active to the current page. Can anyone help me with this?
<div id="sidebar-wrapper" class="sidebar-toggle">
<ul class="sidebar-nav">
<?php
$i=1;
if(count($shipments) > 0)
{
foreach($shipments as $row)
{
$shipment_id = $row['id'];
$containerdest = $row['no']."-".$row['destination'];
?>
<li id="shipment<?php echo $shipment_id; ?>"><?php echo $containerdest; ?>
</li>
<?php $i++;
}
} ?>
<li>
Logout
</li>
</ul>
</div>
</div>
Change your html line with below line
<li id="shipment<?php echo $shipment_id; ?>" class="menu"><a href="<?php echo ite_url("users/get_details/$shipment_id");?>" shipmentid="<?php echo $shipment_id; ?>" ><?php echo $containerdest; ?></a>
And write javascript code as below (assuming you have included jquery library file)
<script>
$(document).ready(function(){
var url = location.pathname;
var arr = mystr.split("/");
var id = arr[2];
$(#shipment'+id).attr('shipmentid');
$('.menu').removeClass('active'); //this will remove all active class after page loading
$('#shipment'+id).addClass('active'); // this will append active class to the current clicked menu
});
</script>

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>

Categories

Resources