I have a href link for my unordered list.
When the page loads for the first time, only the welcome page is visible as expected.
When I click on the list for the first time after the page loads, I get the desired results on the desired div after clicking on the href link on the ul li.
However, if I subsequently click on the other tab, the results are displayed on the one I had clicked before. For example, if i click on href #tab2a, the results will be displayed on #tab2b and vice versa. AJAX will direct results to the div I clicked on previously.
I'm at a loss here! How can I force the results to be displayed in the div that's referenced by the href id tag? I'm using an if else if condition; is this the right approach?
JS
$(document).ready(function() {
$("#tab2").hide();
$("#tab3").hide();
$("#tab6").hide();
$("#tab2a").hide();
$("#tab2b").hide();
$('ul li a').click(function() {
href = undefined;
if (($(this).attr('href')) == "#tab2a") {
var href = $(this).attr('href');
$.ajax({
url: "http://mypage1_action=execute"
}).done(function(data) {
$(href).html(data);
});
$(href).show();
$('form#tab div:not(' + href + ')').hide();
} else if (($(this).attr('href')) == "#tab2b") {
var href = $(this).attr('href');
$.ajax({
url: "http://mypage1_action=execute"
}).done(function(data) {
$(href).html(data);
});
$(href).show();
$('form#tab div:not(' + href + ')').hide();
} else {
$(href).show();
$('form#tab div:not(' + href + ')').hide();
};
});
HTML
<form id="cssmenu">
<ul>
<li class='active'><a href='#tab1'><span>Home</span></a>
</li>
<li class='has-sub'><a href='#tab2'><span>Tab2</span></a>
<ul>
<li><a href='#tab2a'><span>Tab 2a</span></a>
</li>
<li><a href='#tab2b'><span>Tab 2b</span></a>
</li>
<li class='last'><a href='#tab2c'><span>Tab 2c</span></a>
</li>
</ul>
</li>
<li class='has-sub'><a href='#tab3'><span>Tab 3</span></a>
<ul>
<li><a href='#'><span>Tab 3a</span></a>
</li>
<li><a href='#'><span>Tab 3b</span></a>
</li>
<li class='last'><a href='#'><span>Tab 3c</span></a>
</li>
</ul>
</li>
<li class='has-sub'><a href='#tab4'><span>Tab 4</span></a>
<ul>
<li><a href='#'><span>Company</span></a>
</li>
<li class='last'><a href='#tab5'><span>Contact</span></a>
</li>
</ul>
</li>
<li class='last'><a href='#tab6'><span>Contact</span></a>
</li>
</ul>
</form>
<form id="tab" class=".allclass">
<div id="tab1" class='active'>
<h1>Welcome Page</h1>
</div>
<div id="tab2">
</div>
<div id="tab2a">
</div>
<div id="tab2b">
</div>
<div id="tab3">
</div>
<div id="tab6">
</div>
</form>
Here is the fiddle: https://jsfiddle.net/kBoni/1ag0ymh/#&togetherjs=m9pPoV3yoy
This is probably caused because by the time the .done() executes, the value of the href variable may have changed because you've clicked another tab, a simple way to avoid that is to wrap the ajax() code into a new function, and pass the href value as a parameter
function changeTab(href) {
$.ajax({
url: "http://mypage1_action=execute"
}).done(function(data) {
$(href).html(data);
});
$(href).show();
$('form#tab div:not(' + href + ')').hide();
}
$(document).ready(function() {
$("#tab2,#tab3,#tab6,#tab2a,#tab2b").hide();
$('ul li a').click(function() {
href = undefined;
if (($(this).attr('href')) == "#tab2a") {
var href = $(this).attr('href');
changeTab(href);
} else if (($(this).attr('href')) == "#tab2b") {
var href = $(this).attr('href');
changeTab(href);
} else {
$(href).show();
$('form#tab div:not(' + href + ')').hide();
};
});
});
Now, if you also want to have a different url for every tab, (which you probably do), you can add it as a data-attribute to your a and pass it to the function:
function changeTab(href,url) {
$.ajax({
url: url
}).done(function(data) {
$(href).html(data);
});
$(href).show();
$('form#tab div:not(' + href + ')').hide();
}
.
.
.
if (($(this).attr('href')) == "#tab2a") {
var href = $(this).attr('href');
var url = $(this).attr('data-url');
changeTab(href,url);
}
Related
I'm having some real hard time adding class active to the li that contains the current page the site is on. URL = http://polissagethibodeau.com/
Here is the relevant HTML
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>
CSS I am trying to apply
.sf-menu > li.active > a {
background: #c2e078;
}
Here is the script I am trying to use to no success.
$(function() {
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
});
YOU can do it by two or many way. Example project
Source LINK
1.----
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav ul a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
2.----
here's the code if u want to use plain javascript
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
3.----
function setActive() {
$('#nav').find('a').each(function () {
//console.log(document.location.href)
if (document.location.href == "http://......" + $(this).attr('href')) {
$(this).parents("ul").removeClass("hidden-ul");
$(this).parents().addClass("active");
}
});
}
window.onload = setActive;
Use a if statement to check if it is in the url:
<script>
$(function() {
var path = window.location.pathname.substring(1);
if(window.location.href = path) {
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
}
});
</script>
Its because the HREF property of each of those links is going to be equal to a complete URL, not just file.php
You can get around this by using the $= operator which means (ends with)
Note in the DEMO I changed the var path assignment to just services.php so that it would work in the snippet.
Also, use the $(document).ready(function() { trigger to properly add a listener to an event
Note I realize that this example will cause all of the links to services.php to have the class active added to them. To get around this assign a custom class called navlink to each link in the navigation bar and then use
$('.navlink[href$="' + path + '"]:parent').addClass('active');
$(document).ready(function() {
//var path = window.location.pathname.substring(1);
var path = 'services.php#large';
$('a[href$="' + path + '"]:parent').addClass('active');
});
.active {
font-size: 1.75em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
<a href="./" >Home</a>
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>
$(document).ready(function () {
// Get previously stored url
if (sessionStorage.getItem("active-class-url"))
{
strLastUrl = sessionStorage.getItem("active-class-url");
$('.nav > li >a[href="' + strLastUrl + '"]').parent().addClass('active');
}
});
$(document).on(".nav > li > a", "click", function () {
// Remove active class from all ancher tag
$(".nav > li > a").parent("li").removeClass('active');
// Add active class to currenly clicked acnher tag
$(this).parent("li").addClass('active')
// Store value of active calss url. So on page refresh you can get it
sessionStorage.setItem("active-class-url", $(this).attr("href"));
})
The problem is your selector.
Instead of this:
$(".nav > li > a")
Use this:
$(".nav > ul > li > a")
Also remove the . (dot) before your paths, and this will work:
$(document).ready(function() {
var pathname = window.location.pathname;
$(".nav > ul > li > a").each(function() {
var $this = $(this);
if ($this.attr("href") === pathname) {
$this.parent().addClass("active");
}
});
});
Test:
$(document).ready(function() {
var url = window.location.toString();
$('#home a').attr('href',url)
$('#home a').text(url)
$('ul.sf-menu a').filter(function() {
if (this.href != '') {
if (this.href == url) {
console.log(this.href)
console.log(url)
$(this).addClass('active');
}
}
});
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li id="stacksnippets">
stacksnippets
</li>
</ul>
</nav>
try above method I hope it helps you.
I'm loading data from a PHP page with JQuery and it works fine. Now I want that when I click on one of these loaded elements an alert shows the id of the selected element. How can I do? Because I want to send the if later on using ajax. I tried this code, but it didn't work.
HTML
<li><strong>CATEGORY</strong><span> MENU ELEMENTS</span>
<ul class="sub-menu">
<li><a id="id_1" data-target='post_category'>Sub_1</a></li>
<li><a id="id_2" data-target='post_category'>Sub_2</a></li>
<li><a id="id_3" data-target='post_category'>Sub_3</a></li>
<li><a id="id_4" data-target='post_category'>Sub_4</a></li>
<li><a id="id_5" data-target='post_category'>Sub_5</a></li>
<li><a id="id_6" data-target='post_category'>Sub_6</a></li>
<li><a id="id_7" data-target='post_category'>Sub_7</a></li>
<ul>
</li>
JQuery
<script>
$(document).on("click", "a", function() {
alert('worked!');
});
</script>
sending data code
$(document).on("click","a",function(e){
$.ajax({
type: "POST",
data: "id=" + $(this).attr("id"),
url: "post_category.php"
});
});
as I wrote that the alert didn't appear which mean click event in JQuery code doesn't work for some reason.
Thank you for your tips I tried them all, but the found the cause of the problem it's from the script that loading the page using ajax.
<script>
$(document).ready(function(){
//set trigger and container
var trigger = $('#nav ul li a'),
container = $('#container');
//do on click
trigger.on('click', function(e){
/***********/
e.preventDefault();
//get the link location that was clicked
pageurl = $(this).attr('href');
//to change the browser URL to th if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl+'.php');
/* reload content without refresh */
//set loading img
$('#container').append('<div id = "loading">WAIT... <img src = "img/ajax-loader-small.gif" alt="Currently loading" /></div>');
//change img location to center
$("#loading").css({"position": "absolute", "left": "50%", "top": "50%"});
//get the trigger to reload the contents
var $this = $(this),
target = $this.data('target');
container.load(target + '.php');
return false;
});
});
// fix url in the browser when click on backward and foreword arrows
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#container').html(data);
}});
});
</script>
I really don't know which part that cause this problem. Please help/
I think the probelm is with your identification of which element is clicked. I would do it this way: First, in your html move the id to the li element
<ul>
<li><strong>CATEGORY</strong> MENU ELEMENTS
<ul class="sub-menu">
<li id="id_1"><a data-target="post_category"></a>Sub_1</li>
<li id="id_2"><a data-target="post_category"></a>Sub_2</li>
<li id="id_3"><a data-target="post_category"></a>Sub_3</li>
<li id="id_4"><a data-target="post_category"></a>Sub_4</li>
<li id="id_5"><a data-target="post_category"></a>Sub_5</li>
<li id="id_6"><a data-target="post_category"></a>Sub_6</li>
<li id="id_7"><a data-target="post_category"></a>Sub_7</li>
</ul>
</li>
</ul>
You should then be able to get the id with:
jQuery("#container-fluid > section > div > div.box-body > ul > li > ul").children().on("click", function() {
alert('worked!');
alert(this.id);
});
Try below code. It's working fine.
<li><strong>CATEGORY</strong><span> MENU ELEMENTS</span>
<ul class="sub-menu">
<li><a id="id_1" class="abc" data-id="id_1" data-target='post_category'>Sub_1</a></li>
<li><a id="id_2" class="abc" data-id="id_2" data-target='post_category'>Sub_2</a></li>
<li><a id="id_3" class="abc" data-id="id_3" data-target='post_category'>Sub_3</a></li>
<li><a id="id_4" class="abc" data-id="id_4" data-target='post_category'>Sub_4</a></li>
<li><a id="id_5" class="abc" data-id="id_5" data-target='post_category'>Sub_5</a></li>
<li><a id="id_6" class="abc" data-id="id_6" data-target='post_category'>Sub_6</a></li>
<li><a id="id_7" class="abc" data-id="id_7" data-target='post_category'>Sub_7</a></li>
<ul>
</li>
<script type="text/javascript">
$(".abc").click(function () {
var id_value = $(this).data('id');
alert(id_value);
});
</script>
I believe you are setting up click events before the links are added to the dom. Ajax calls are a little bit different than the regular functions. They don't block your code so when you do an ajax call, javascript calls the function and doesn't wait for the response. It goes and implements the rest of the functions.
Simpler version of your function
$.get(url, function (data) {
// success -> Usually just calling your function here solves the problem.
}).done(function () {
setupClickListener(); // If it doesn't append this to it for extra security.
});
function setupClickListener(){
$(document).on("click", "a", function() {
alert('worked!');
});
}
The problem is return false in the loading receipt.
I removed return false and kept e.preventDefault(); so it will do the same thing.
After applying styles of Codrops in nav bar, I cannot make links go to the area id in a single page.
If I press "Clients" (for example), the link does not go to the id Clients area.
I need help in identifying the source of the problem.
Here is my HTML:
<nav class="menu menu--ferdinand">
<ul class="menu__list">
<li class="menu__item">
<a class="menu__link" href="#Services">Services</a>
</li>
<li class="menu__item">
<a class="menu__link" href="#Clients">Clients</a>
</li>
<li class="menu__item">
<a class="menu__link" href="#Us">About Us</a>
</li>
<li class="menu__item menu__item--current">
<a class="menu__link" href="#Contact">Contact</a>
</li>
</ul>
</nav>
script on the bottom of my index.html (I have classie.js, clipboard.min.js on js folder)
<script src="js/classie.js"></script>
<script src="js/clipboard.min.js"></script>
<script>
(function() {
[].slice.call(document.querySelectorAll('.menu')).forEach(function(menu) {
var menuItems = menu.querySelectorAll('.menu__link'),
setCurrent = function(ev) {
ev.preventDefault();
var item = ev.target.parentNode; // li
// return if already current
if (classie.has(item, 'menu__item--current')) {
return false;
}
// remove current
classie.remove(menu.querySelector('.menu__item--current'), 'menu__item--current');
// set current
classie.add(item, 'menu__item--current');
};
[].slice.call(menuItems).forEach(function(el) {
el.addEventListener('click', setCurrent);
});
});
[].slice.call(document.querySelectorAll('.link-copy')).forEach(function(link) {
link.setAttribute('data-clipboard-text', location.protocol + '//' + location.host + location.pathname + '#' + link.parentNode.id);
new Clipboard(link);
link.addEventListener('click', function() {
classie.add(link, 'link-copy--animate');
setTimeout(function() {
classie.remove(link, 'link-copy--animate');
}, 300);
});
});
})(window);
</script>
Areas (example):
<section id="Clients" class="Clients">
</section>
<section id="Services" class="Services">
</section>
ev.preventDefault() Prevents a link from doing it's default thing (i.e. follow the link to a new page or bookmark).
My HTML code looks like this:
<div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
<div class="menu_section">
<ul class="nav side-menu">
<li>
<a>
<i class="fa fa-home"></i>home
<span class="fa fa-chevron-down"></span>
</a>
<ul class="nav child_menu" style="display: none">
<li>
Dashboard
</li>
<li>
dashbord2
</li>
</ul>
</li>
<li>
<a>
<i class="fa fa-edit"></i>form
<span class="fa fa-chevron-down"></span>
</a>
<ul class="nav child_menu" style="display: none">
<li>
general form
</li>
<li>
form validation
</li>
</ul>
</li>
</ul>
</div>
</div>
to add/remove class based on current url, i am using this:
$(function () {
var url = window.location.href;
$('#sidebar-menu a[href="' + url + '"]').parent('li').addClass('current-page');
$('#sidebar-menu a').filter(function () {
return this.href == url;
}).parent('li').addClass('current-page').parent('ul').slideDown().parent().addClass('active');
});
It works, but when i click this link
dashbord2
the class="current-page" doesn't change to current path url
How i fix this?
Your issue arises from the page not being reloaded when you click on the link with hash in it, while your code only executes on page load, or dom ready to be exact. The solution is to whether use window's hashchange event (not supported in < IE8) or, like #sirrocco mentioned, use click event with setTimeout to detect the change of hash:
function setCurrentMenuPage() {
var url = window.location.href;
var anchors = $('#sidebar-menu a');
anchors.parent('li').removeClass('current-page');
anchors.filter(function () {
return this.href == url;
}).parent('li').addClass('current-page').parent('ul').slideDown().parent().addClass('active');
}
$(function () {
setCurrentMenuPage();
$('#sidebar-menu a').on('click', function (e) {
if ($(this).attr('href').indexOf("#") >= 0) {
setTimeout(function () {
setCurrentMenuPage();
}, 100);
}
});
});
Hope that helps.
<div id="logo"><!-- logo -->
My Site
</div><!-- end logo -->
<?php
if ($_SESSION['uid'] == "")
{
echo "<div id='main_menu' class='log'>You are not logged in • <a href='login.php'>Login</a><br \></div>";
exit();
}
else
{
echo "
<div id='main_menu'>
<ul>
<li class='bar'> </li>
<li><a href='index.php' id='ajax_link'>Edit Site</a></li>
<li class='bar'> </li>
<li><a href='docs.php' id='ajax_link'>My Documents</a></li>
<li class='bar'> </li>
<li><a href='contacts.php' id='ajax_link'>Web Contacts</a></li>
<li class='bar'> </li>
<li><a href='social.php' id='ajax_link'>Social Media</a></li>
<li class='bar'> </li>
You are logged in as ".$_SESSION['username']." • <a href='logout_parse.php'>Logout</a><br \>
</ul>
</div>
";
}
?>
I've got this menu system built(above) and i'm using ajax and jquery to change in and out the main content(below) depending on the menu item selected.
var hash = window.location.hash.substr(1);
var href = $('#ajax_link').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').fadeOut('fast',loadContent);
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length);
function loadContent()
{
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent()
{
$('#content').fadeIn('normal');
}
return false;
});
however for some reason this code is affecting the login and logout links as well and i don't want that to happen.
I only recently added #ajax_links to try fix this problem as i was using #main_menu ul li a and #logo a before.
Can anyone tell me how i can fix this
First off, id attribute should be unique. Change all those links to use a class instead:
<li><a href='index.php' class='ajax_link'>Edit Site</a></li>
Now use that to improve the selector
$('a.ajax_link').click(function(){
....
And
$('.ajax_link').each(function(){
....