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

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");
});
});

Related

Add/Remove classes from navigation loaded with Jquery

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

add class to a component in jsf template

I'm using a template for my website but I want to add a class to <li> element when clicking it , I can do it already as i saw the result in the debug mood but when i moved to this page the class="active" which i added is removed again.
Here is my img in debug mood and the script which i use.
So how can I save the added class to this element?
<script>
$(document).ready(function () {
$("#liEmpCreate").click(function () {
console.log("rerererererer ay2 ay2 ay2 ");
$("#liEmpCreate").addClass("active");
});
});
</script>
result in debug mood before redirect to this page
Finally I found the answer :) .
As I mentioned above in the question , i wanted to add this class to an element of sidebar which refers to the pages i opened. So i have all these elements in all pages, then i put an id foreach tag and tried to use the same script in each page separately , but unfortunately it doesn't work either.
So i tried to put my script everywhere in my page but when i put it after my form and before </ui:define> i found the console.log appears in the browser console, but it doesn't work as i wished because of this code is called and then the page is rendered again. finally i used the below code and it worked correctly.
<script>
$(window).on('load', function() {
$("#liEmpCreate").addClass("active");
});
</script>
<h:outputStylesheet library="js2" name="jquery-3.2.1.min.js"/>
</ui:define>

javascript onclick null in custom js file

I'm trying to simply detect clicking an A link to display an Alert box. Whenever I place the script inside the php file my a link is located, it works fine, but whenever I place it in my custom JS file, it doesn't detect it, and I get the error 'Uncaught TypeError : Cannot set property "onclick" of null'.
The link between the php page and custom js page is definitely working, as I have previous working code on the page. It simply wont detect my A link it its located in an external script.
HTML
<a id="ConfirmHolidayClose" href="#">
<img src="assets/img/close-button.png" alt="Holiday-request-close-button"
class="CloseButton" />
</a>
JAVASCRIPT
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
UPDATE - Forgot to mention sorry, my a link is nested inside div called 'ConfirmHoliday'.
I have JS code manipulating the ConfirmHoliday div inside my Custom JS, so it cant be loading after because it is finding its parent div perfectly well at the moment.
The javascript file runs before the element is created, thus it doesn't exist. To solve this, you have couple options:
1) Surround the code with a window.onload function
window.onload = function () {
// Your code here
};
2) Put it in a separate js file and add a defer property to the script tag.
<script src="yourScript.js" defer="defer"></script>
3) Put the script tag after the anchor tag
It's trying to access the ConfirmHolidayClose element before it exists maybe? Where is your JS loaded in your page? I'm guessing in your <head>
A few solutions:
1) Move your script to bottom of page just above </body>
2) wrap your JS in dom ready function, this ensures no JS will run until the DOM tree exists. Easiest with jQuery, example below...
jQuery example
$(function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Vanilla example
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});

Can't call javascript from ajax div

I have some content loaded in my page using ajax. I want to run a JS function when some anchors are clicked. These anchors belongs to the code loaded using ajax. Both the ajax request and the JS function are located in a separate JS file, inside a jQuery(document).ready(function() {.
I have a few dozens functions in this JS file, and they're running fine, but this specific function is the only one called by code retrieved using ajax, and it is not working. My code:
html main file:
<!-- code -->
<div id="ajaxContentGoesHere">
<!-- content inserted here by ajax function -->
<td>Editar</td>
</div>
<script src="/js/myJS.js"></script>
</body>
/js/myJS.js file:
jQuery(document).ready(function() {
/*some other functions here*/
$("[id^='aLancamentoEdit']").click(function(){
console.log(1);
}
});
I tried to put the $("[id^='aLancamentoEdit']").click(function(){ inside the html main file, in a tag after the /js/myJS.js call. Didn't work.
Also tried to change the selector to match my anchor class (I declared a class for this). No success either. Finally tried also to put a name in the function and call it on onclick="" inside the anchor. Failed again.
What am I doing wrong?
Since the element by id starting with 'aLancamentoEdit' is dynamically added by ajax, you need to bind click handler to parent:
$('#ajaxContentGoesHere').on('click', "[id^='aLancamentoEdit']", function() {
console.log(1);
});
Use .on() for dynamic element events (ajax content in your case). Try:
jQuery(document).ready(function() {
/*some other functions here*/
$("#ajaxContentGoesHere").on("click","[id^='aLancamentoEdit']",function(){
console.log(1);
}
});

$(document).ready can't replace js declared at bottom of the page, but I need to have the script at the top

I have JQuery based tab navigation that only works if it is placed after the html for the menu. It works if it's placed at the end too, but breaks when I put the same script in $(document).ready ath the top.
I thought that this (placed at the top of the page):
<script type="text/javascript">
$(document).ready(function(){
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
});
</script>
would be the same as this:
<script type="text/javascript">
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
</script>
</html>
Which is placed at the bottom of the page and works. How would I be able to put the function at the top or even include it from a separate file?
I had this problem and I had used this in the head after the jquery include link:
$(document).ready(myfunction());
This failed due to objects not being loaded. I should have wrapped my call in a function:
$(document).ready(function () {
myfunction();
});
This worked as expected only after the document was properly loaded.
The reason it is recommended to place the script at the end of the page , is so that the HTML elements are loaded onto the page before you try to access them..
No matter where you place the code it is better to wrap in DOM ready event which makes sure the complete HTML document is properly loaded before you try to access the elements in the page..
Maybe in your case
<script type="text/javascript">
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
</script>
seems to be working when not encased in DOM ready is the function is not accessible as it's scope is being blocked by DOM ready

Categories