Run javascript on dynamically loaded content for ajax based website - javascript

I an currently designing a ajax based navigation website. The problem I encountered is when I try to run jquery on dynamically loaded content it doesn't work.
Here is what I did:
index.html
<html>
<head>
<title>Testing Dynamic Content</title>
<link href="style.css" rel="stylesheet"/>
<script src="http://localhost/jquery.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="main">
<div class="content">
<ul class="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</div>
</div>
<script>
$('.list').greenify();
</script>
</body>
</html>
2.html
<html>
<head>
<title>Testing Dynamic Content</title>
<link href="style.css" rel="stylesheet"/>
<script src="http://localhost/jquery.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="main">
<div class="content">
<span id="hello">Content</span>
</div>
</div>
<script>
$('#hello').on('click',function(){
$('.main').load('index.html .content');
$('.list').greenify();
});
</script>
</body>
</html>
style.css
.list{
color:#f00;
}
main.js
$.fn.greenify = function() {
this.css( "color", "red" );
};
The problem is in the $('list').greenify();. When I load content of index.html on 2.html using .load() the content loads in red color as defined in css. When I run $('list').greenify() on this loaded content it doesn't works.
How can I run mak this happen to run JavaScript on dynamically loaded content?
I need to do this to make a slideshow run on dynamically loaded webpage. And slideshow is not working.

issue is your code run before your page successfully loaded, move your code to document ready event:
$(document).ready(function(){
$('.list').greenify();
})
and jQuery load is async you need to run your javascript in success function
$('.main').load('index.html .content', function() {
//will execute when load successfully
$('.list').greenify();
});

You should bind the events like this then only your script will affect on dynamic DOM elements
$('body').on('click','#hello',function(){
$('.main').load('index.html .content');
$('.list').greenify();
});

Related

jQuery click not being recognized

Im creating a signup page for my website but it is not responding to a click. I have the jQuery in a seperate file called signup.js. I know it is linked properly because an alert works.
Any help would be apreciated. Thanks
html:
<html>
<head>
<title>Sign Up</title>
<script src="JS/jquery-3.1.1.min.js"></script>
<script src="JS/signup.js"></script>
<link rel="stylesheet" href="CSS/signup.css">
<link rel="stylesheet" href="CSS/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<button id="signup-button">Sign Up</button>
</div>
</div>
</body>
</html>
jQuery:
$("#signup-button").click(function() {
alert("clicked");
});
You are trying to get the element before loading the DOM element so it won't get attach the handler to the element since it's not present at that point. To make it works wrap it using document ready handler or move the script tag after the element in the markup.
$(document).ready(function(){
$("#signup-button").click(function() {
alert("clicked");
});
});
Since the latest jquery update, everything is pointed on .on so .click is no longer valid, use
$('#signup-button').on('click', function(){//code here})
instead, and make sure you put it in a DOM ready
Make sure your code is executed on document ready.
$(function(){
$("#signup-button").click(function() {
alert("clicked");
});
});
I recommend you just put your jquery in the head, and the other javascript in the end of your body, because your js file is probably be "read" before your jquery file.
<html>
<head>
<title>Sign Up</title>
<script src="JS/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="CSS/signup.css">
<link rel="stylesheet" href="CSS/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<button id="signup-button">Sign Up</button>
</div>
</div>
<script src="JS/signup.js"></script>
</body>
</html>
and change your js file to:
$(function(){
$("#signup-button").click(function() {
alert("clicked");
});
});
because the $(function(){}); waits until the DOM is load and can be manipulated.

Multiple javascripts on one page

I'm working on a site that has 20+ pages that get changed every few months. I decided to make a script to load the navbar,nav, and footer as they are on every page.
<!DOCTYPE HTML>
<html lang="en">
<head>
<link href="../css/bootstrap-dropdownhover.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../css/myCss.css">
</head>
<body>
<navbar></navbar>
<div id="nav"></div>
<div class="content"></div>
<footer></footer>
</body>
<script src="../js/loader.js"></script>
<script src="../js/bootstrap-dropdownhover.min.js"></script>
</html>
Im using loader.js to load in the navbar, nav, and footer.
$(document).ready(function() {
$("navbar").load("../pageFramework/navbar.html");
});
$(document).ready(function() {
$("#nav").load("../pageFramework/navpills.html");
});
$(document).ready(function() {
$("footer").load("../pageFramework/footer.html");
});
This loads all pages perfectly, but when I try to hover my nav the dropdownhover.min.js does not work to show my dropdown menus. When I put the navbar html directly on the page and remove loader.js it works perfectly.
Once your header/nav/footer have been loaded you will need to re-initialize bootstrap; see Bootstrap Select - reinitialize on dynamically added element
You need to load bootstrap-dropdownhover.min.js in the callback of load(navbar.html). See: https://api.jquery.com/jquery.getscript/

Hiding third party script from particular page

i have a HTML template in which i have used a third party javascript code. this particular code provides an chat option.i have added this script in my header.html so that it gets displayed in all the pages. however i dont want this to display in my login page.i want this to be displayed only after logging in.
How do i hide this from a particular page(here login.html)?
Header.html
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="bower_components/weather-icons/css/weather-icons.min.css">
<link rel="stylesheet" href="styles/main.css">
</head>
<body data-ng-app="app" id="app" class="app" data-custom-page="" data-off-canvas-nav="" data-ng-controller="AppCtrl" data-ng-class=" {'layout-boxed': admin.layout === 'boxed' } ">
<section data-ng-include=" 'views/index.html' " id="header" class="header-container" data-ng-class=" {'header-fixed': admin.fixedHeader} " data-ng-controller="HeaderCtrl" data-ng-intro-options="introOptions" data-ng-intro-method="startIntro" data-ng-intro-autostart="true"></section>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="scripts/vendor.js"></script>
<script src="scripts/jquery.leanModal.min.js"></script>
<script src="scripts/ui.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/product_listing.js"></script>
<script src="scripts/angular-cookies.js"></script>
<script id="SettingsScriptTag">
**Third Party script Goes here**
</script>
</body>
</html>
The above header.html is included in all the other templates. hense the thrid party script runs in login page too. I need to hide this in login page.
If you're using jQuery (which... I think you are...?)
$(function () {
if (window.location.pathname !== '/login.html') {
// Third-party script goes here
}
});
If Using jquery .remove() is used to remove the html elements. So you can write this script on document ready of the login page.
$(document).ready(function(){
$( "#SettingsScriptTag" ).remove();
});

How to load stylesheets after loading and displaying page without any style

I was thinking instead of loading everything in parallel. I will allow to load and display the basic no-styled layout and then will load the css file after page has finished loading, but being a newbie in Javascript. I am not able to do this.
Till now I have tryed:
<head>
<script type='text/javascript'>
function addstyle()
{
document.getElementBytype('text/css').href='style.css';
}
</script>
<link rel="stylesheet" type="text/css" href="">
</head>
<body onload="addstyle()">
<h1>Good Morning</h1>
<p>Hello whats up</p>
<p>Hope you will have a great day ahead</p>
</body>
Here as you can see, I am trying to load style.css after the page is displayed in the browser, but it is not working.
Try this:
<head>
<script type='text/javascript'>
function addstyle()
{
document.getElementById('style').href='style.css';
}
</script>
<link rel="stylesheet" id="style" type="text/css" href="">
</head>
<body onload="addstyle()">
<h1>Good Morning</h1>
<p>Hello whats up</p>
<p>Hope you will have a great day ahead</p>
</body>
If you are using jQuery you can do something like this:
$(document).ready(function(){
var $style_element = $(document.createElement('style'));
$style_element.attr({href:'http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css', rel:'stylesheet', type:'text/css', id:'some_id'});
$('head').append($style_element);
});

jquery mobile didn't append div to content

I have a script which should append some element to the Content div, but it didn't work.
As you see the content of the "messageBox" is arrives from a php file which select the mysql table and the data from it.
Here is the JS file's content:
function getWallMsg(){
$.getJSON('SELECT_uzenofal.php?callback=?',function(data) {
data.forEach(function(e){
$('#posts').append($('<div class="messageBox">'+'<img src="img/profilok/'+e.kep+'"/>'+'<p class="name">'+e.nev+'</p>'+'<p>'+e.uzenet+'</p>'+'<p class="time">'+e.ido+'</p>'+'</div>'));
});
});
}
$(document).ready(function(){
drawNavbar();
getWallMsg();
});
And the html:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" >
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="fal">
<!-- header -->
<div data-role="header">
<h3>
Üzenőfal
</h3>
</div>
<!-- content -->
<div data-role="content" id="posts">
</div>
<!-- footer -->
<div class="nav" data-role="footer" data-position="fixed" data-theme="a"></div>
</div>
</body>
What should I do?
This should be changed:
$(document).ready(function(){
drawNavbar();
getWallMsg();
});
to this:
$(document).on('pagebeforeshow', '#fal', function(){
drawNavbar();
getWallMsg();
});
Basically document ready should not be used with jQuery Mobile, to find out more about this take a look at this ARTICLE, to be transparent it is my personal blog. Or find it HERE.
Basically you are trying to append it on document ready when page content is not loaded into the DOM. Instead proper jQuery Mobile page event, like pagebeforeshow, should be used.
EDIT :
You were adding an incorrect id to the pagebeforeshow even. It should work now.
could not comment so posting as answer.
$('#posts').append($('<div class="messageBox">'+'<img src="img/profilok/'+e.kep+'"/>'+'<p class="name">'+e.nev+'</p>'+'<p>'+e.uzenet+'</p>'+'<p class="time">'+e.ido+'</p>'+'</div>'));
have you tried changing above to
$('#posts').append('<div class="messageBox">'+'<img src="img/profilok/'+e.kep+'"/>'+'<p class="name">'+e.nev+'</p>'+'<p>'+e.uzenet+'</p>'+'<p class="time">'+e.ido+'</p>'+'</div>');

Categories