Add/Remove classes from navigation loaded with Jquery - javascript

I am loading in the content of my sidebar navigation with jquery from a nav-content.html file so I don't have to update it on every page each time it updates.
What I am trying to do is when on a specific page, the sidebar nav with uncollapse based on what category that page is on.
I am trying to target elements in that loaded nav to be active when on certain pages and it only works when the nav is hard coded into the page's html but it doesn't work when I load it in from the nav-content.html file with jquery.
I did noticed when i view the source code on browser it doesn't actually paste in the html but still displays it which I think is the disconnect but I am not 100%. Not sure if I should look into different way to load it in or if my jquery is the issue.
Any insight would be greatly appreciated.
HTML:
<nav>
<div id="sidebar">
<div id="sidebar-content">
<!-- nav loads here from nav-content.html -->
</div>
</div>
</nav>
Jquery:
/*Loads the Nav */`
window.onload = function(){
$.get("nav-content.html", function(data){
$("#sidebar-content").html(data);
})
}
/* changes classes within the loaded nav based on what page it's on */
$(document).ready(function() {
$('ul#devSubmenu').removeClass('collapse'),
$('ul#appStackSubmenu').removeClass('collapse'),
$('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
$('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
});
I asked this a few days ago but this is a rephrased/re-explained of deleted post.

Two things to get you on the right path.
1) jQuery's get() does not load an HTML file. You might mean to use load() to get your sidebar content: https://api.jquery.com/load/
2) $(document).ready fires before window.onload. See: window.onload vs $(document).ready()
In order to ensure that your content is loaded before modifying the classes, you can make your modifications in the callback from load() (the function passed as the second parameter to load()).
Something like [untested]:
$(function() {
$( "#sidebar-content" ).load( "nav-content.html", function() {
$('ul#devSubmenu').removeClass('collapse'),
$('ul#appStackSubmenu').removeClass('collapse'),
$('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
$('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
});
});
The wrapping $(function() { ... }) is just jQuery shorthand for $(document).ready();

Related

How to target Jquery Injected Nav

I am loading in my navigation with jquery from a nav.html file so I don't have to update it on every page each time it updates.
I am trying to target elements in that loaded nav to be active when on certain pages and it only works when the nav is hard pasted into the page's html but it doesnt when I load it in from the nac-content.html file.
I did noticed when i view the source code on browser it doesnt actually paste in the html but still displays it which I think is the disconnect but I am not 100%. Not sure if I should look into different way to load it in or if my jquery is the issue.
Any insight would be greatly appreciated.
HTML:
<nav>
<div id="sidebar">
<div id="sidebar-content">
<!-- nav loads here from nav-content.html -->
</div>
</div>
</nav>
Jquery:
/*Loads the Nav */`
window.onload = function(){
$.get("nav-content.html", function(data){
$("#sidebar-content").html(data);
})
}
/* changes classes within the loaded nav based on what page it's on */
$(document).ready(function() {
$('ul#devSubmenu').removeClass('collapse'),
$('ul#appStackSubmenu').removeClass('collapse'),
$('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
$('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
});
You could do something like this
$(document).ready(function () {
// DOM has been parsed
$.get("your/url", function (data) {
var $navContainer = $("#sidebar-content");
$navContent = $(data); // build a jQuery object from your html markup
// do your updates using the find method of jQuery objects
$navContent.find("ul#devSubmenu").removeClass("collapse");
// ...
$navContainer.append($navContent); // assuming the container is empty.
});
});
window.onLoad gets executed after $(document).ready
You could use
document.addEventListener("DOMContentLoaded", function(event) {
$.get("nav-content.html", function(data){
$("#sidebar-content").html(data);
})
});

Can I add/remove class on element loaded by load() function?

I have a navbar with class called "active" with some CSS styling. The navbar is used on a number of subpages so I figured out that instead of repeating the code on all the subpages I will load navbar with load() function.
The problem is that with the content loaded by the load() function I cannot remove the class using removeClass(). The navbar is loaded, I can see the tags in inspector, and all seems to be OK. The code is working if I put the navbar manually in the HTML.
I've tried to move the script tag that deletes the class after the CDN script, but it does not help (the idea was to remove class on the fully loaded page). What am I missing?
I'm using the following code to load the navbar:
$(function(){
$("#includeNavbar").load("../partials/navbar.html");
});
Then I put a tag in HTML:
<div id="includeNavbar"></div>
Then I use <script> tag in the HTML, but below code does not remove class:
<script>
$("li").removeClass("active");
$("li").eq(1).addClass("active");
</script>
The issue is where you're calling removeClass() and addClass() from. You need to do it in the callback of the load(), to ensure that the content exists in the DOM when you execute those calls:
$(function(){
$("#includeNavbar").load("../partials/navbar.html", function() {
$("li").removeClass("active").eq(1).addClass("active");
});
});

jQuery-Page not loading correctly

I recently used accordion jquery to help me expand/collapse content ( like a drop-down menu )..I used this script and placed it in the <body>
Script:
jQuery(document).ready(function($)
{
$("#accordions-727.accordions").accordion({
active: "",
event: "click",
collapsible: true,
heightStyle: "content",
animated: "swing",
})
})
The script is working fine but the page is not loading correctly..When I view or refresh the page, all the contents inside the drop-down menu becomes visible but once the page finishes loading everything becomes fine..Now how can I fix this?..Should I place the script in the <head>?
This is using jQueryUI accordion implicitly #Stew.
You have a wrong attribute in your accordion setup code, use the animate in place of animated.
Take a look in this API documentation: http://api.jqueryui.com/accordion
And it's the original component demonstration: http://jqueryui.com/accordion/
I suggest you to take a look in your jQuery files too, if they are OK and in the correct order (in <header> section).
Another point is to put your JavaScript in <header> section of your HTML and be sure you have no conflict or using older jQuery files versions than the component needs.
Hope it helps.

Execute javascript after page transition

I am trying to create an dynamic phonegap app using jquery mobile but am having some issues loading javascript when going to a page using transition.
My index page look like this:
<body>
<div data-role="page" id="homePage">
<div data-role="header" data-theme="c" data-position="fixed">
<h1>My Page</h1>
</div>
<div data-role="content" id="pageName">
<ul data-role="listview">
<li>This is a test</li>
</ul>
</div>
</div>
</body>
On my "pages/clubpage,html" I have included below in the head:
$(document).on('pageshow', function (){
alert("I am here!");
});
Somehow I don't get the alert? What am I doing wrong?
Please help and thanks in advance :-)
<------- EDIT --------->
I am actually trying to goto page 2 and that page has an dynamicly generated listview like this:
$(document).on('pageshow', '#clubPage',function (){ // GET THE CURRENT CLUBPAGE //
var clubid = getUrlVars()["clubid"];
$.getJSON("http://mypage.com/groupmenu.php?callback=?&userid="+userid+"&clubid="+clubid,
function(data){
var content = []
$.each(data , function(i,val){
content.push(val.list);
});
$("#mathes_list_count").html(content.join(""));
$('#mathes_list_count').listview('refresh');
});
});
Now my question is... Can I generate this before the transition is made?
You are not getting anything because delegated page events needs 2 objects, one original like document and a second one, same one you are missing. In your case it is a page id:
$(document).on('pageshow', '#homePage',function (){
alert("I am here!");
});
But this isn't your real problem.
To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.
First page is loaded normally. Its HEAD and BODY is loaded into the DOM, and they are there to await other content. When second page is loaded, only its BODY content is loaded into the DOM.
Read more about it here in my other answer, you will also find solutions and examples: Why I have to put all the script to index.html in jquery mobile
EDIT :
There are two possible solutions here. You can executed getJson on a page before, store its content and rebuild it on an another page during the pagebeforecreate event. Take a look at my other answer how you can store data between transitions, search for topic Data/Parameters manipulation between page transitions : jQuery Mobile: document ready vs page events.
Or you can initialize page transition and load/build all data during the pagebeforecreate or pageinit event. Which is still better then doing it during the pageshow event.
In my opinion, solution 1 is a better solution because transition wont suffer and data will not magically appear if pageshow event is used.

jQuery each doesn't work with certain classes, or classes in general?

I'm using Phonegap to build a small (test only) Macrumors application, and remote hosts actually work (there is no same host browser restrictions). I am using the jQuery Load() function to load the contents of the Macrumors homepage http://www.macrumors.com/ into a bin, hidden div, then the each function to loop through all the article classes to show the title in a box with a link to the page.
The problem is, after the Macrumors HTML content is loaded, the each function doesn't work with the article class. Also, in the load function (which allows you to specify certain selectors, id's and classes included, to only load in those sections of the page) the class doesn't work; none of the classes do, in both the load function and each function. And many Id's don't work in the each function either.
Can anybody explain this to a noob like me?
Here is the code:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content');
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
}
And the HTML stuff
<body onload="onBodyLoad()">
<div id="bin">
</div>
<div id="content">
</div>
</body>
I sincerely apologize if there's some very simple mistake here that I'm missing; I'm a major JS newbie.
.load() is asychronous. It hasn't completed yet when you're executing .each(). You need to put your .each() and any other code that wants to operate on the results of the .load() in the success handler for .load().
You would do that like this:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I'm also guessing that your .each() function isn't working quite right. If you want to get the link out of each .article object, you would need your code to be like this so that you're only finding the <a> tag in each .article object, not all <a> tags in the whole document:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $(this).find('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}

Categories