In my site's index.html I have a div element that changes when a menu item gets clicked (with jquery). The pages that get inserted into this element all have some javascript functions in them. However, I load my javascript files in the index.html right before the body closes. These files don't 'reload' when this div element changes, so the javascript doesn't work on these pages. How would I fix this issue? Do I have to reload the javascript files on the change of the element? And if so, how?
edit:
Sorry, these are the codes for the page inserts:
$("li.load-page").click(function() {
var pagina = $(this).data("page") + ".html";
console.log(pagina);
$("#main-content").load(pagina);
});
main-content is an empty div in index.html.
In one of the pages that gets inserted I use the jquery accordion in my html for example, but it doesn't work since it's included in the head, and the page doesn't refresh on insertion:
$(function() {
$( "#accordion" ).accordion({
collapsible: true,
heightStyle: "content"
});
});
EDIT2: I have simulated my problem here: https://jsfiddle.net/ktoeon2f/2/
<script type="text/javascript" id="jsid">
//your script here
</script>
after onchange call
eval(document.getElementById("jsid").innerHTML);
after load
$("li.load-page").click(function() {
var pagina = $(this).data("page") + ".html";
console.log(pagina);
$("#main-content").load(pagina);
eval(document.getElementById("jsid").innerHTML);
// give an id (jsid) to script tag inside your loaded page
});
The problem was solved in this thread: jQuery: Changing the CSS on an element loaded with ajax?
The solution was to load the other function(s) in the succes function of an ajax call:
$('#main-content').load(
url,
function(){
accordionFunction();
}
);
Related
I'm trying to show a div that That indicates that the page is loading, for the load I use the jquery load event, however, the load div always stays on the page and there is no hidden end load, my code is this:
$("#mydiv").fadeIn("fast");
$('#page').load('myphp.php', { 'data': id },function(){
$("#mydiv").fadeOut("fast");
});
Hide the div when the document finishes loading via
$(document).ready(function() {
$("#mydiv").fadeOut("fast");
});
(include this code after the rest of your JS in the header), e.g.
HTML headers
JS/jQuery
this^
CSS link
HTML body contents
you can use $('#page').ajaxStart(callback); and $('#page').ajaxStop(callback);.
look here:
https://api.jquery.com/ajaxStart/
https://api.jquery.com/ajaxStop/
I have a problem with my code , iam using Html 5 history and its work fine in getting contents and changing url but when i refresh the page its show only the content without full page with css and here my code :
<script type="text/javascript">
$(function() {
$('.menuAnchor').click(function(e) {
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.get(url, {}, function (data) {
$(".contn_btm_mid_bg").html(data);
//$.validator.unobtrusive.parse(".contn_btm_mid_bg");
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>
I use history.js to change my URL using ajax and it works fine for me. Your CSS shouldn't really change if you have it linked in your document. Are you overwriting it?
Declare your CSS in the head of the page that you're doing the ajax call on and on ajax load only update the DIV or whatever element with the contents of the ajax call. I do that with this plugin and it works great for me. My CSS is always there even on page refresh.
<html>
<head>
<link rel="stylesheet" type="text/css" href=" linktoyourfile.css" media="screen">
<!--js files etc -->
</head>
<body>
<div class="contn_btm_mid_bg"><!--ajax contents--></div>
</body>
</html>
EDIT:
Since I can't see your HTML or structure I will just tell you how I might do it based on your comment.
Don't call the whole page. Just call the div that contains the content you want to import via ajax. Not the whole page. Link the CSS on all your included pages in the header. Then use a DIV to hold the content, when you call that page, just call the id of the DIV not the entire page. example
Your other pages:
Then in your ajax call if your divs have the same class in all the pages you can do this below. Make sure you link your CSS in your other pages too.
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.get(url, {}, function (data) {
$(".contn_btm_mid_bg").html($(data).find('.contn_btm_mid_bg').html());
//$.validator.unobtrusive.parse(".contn_btm_mid_bg");
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
In page Index.html there is a selectbox called #choose_content_to_load and a div called #get_loaded_content
<select id="choose_content_to_load">
<option>Some content from page content.html and div #content</option>
</select
<div id="get_loaded_content">
As seen in the selectbox option there is a page called content.html that contains a div called #content. In the current situation the div #content get loaded into #get_loaded_content when click on the option by using this script:
$(document).ready(function(){
$("#choose_content_to_load").change(function(){
var selectedOption = $('#choose_content_to_load :selected').val();
$containerDiv = $('#get_loaded_content');
$containerDiv.html("");
switch (selectedOption)
{
case "Some content from page content.html and div #content":$containerDiv.load( "content.html #content" , function(){$(document).trigger("reload_javascript");});break;
}
return true;
});
});
As you see the script also trigger a "reload" of all the scripts "reload_javascript". This is becuse the div #content have some more design elements that needs to be executed at the load in. These scripts looks like this:
$(document).on("ready reload_javascript" ,function() {
script
});
This works fine and all the loaded elements initializes and works, this becuse Index.html and content.html share the same design scripts (same .js file) so the scripts just need to "run again" to work. Now to the problem, the div #content need to have a larger script that only execute when the div is being loaded into #get_loaded_content in Index.html. Its not good to have the script in the .js file that both index.html and content.html share becuse its alot of code.
So the new script need to be put direct into the #content html using tags and execute when this div is being loaded in.
First I thought the new script will run just by adding the reload_javascript but then I realised that dident execute the script just initialize it (I think). I hope somebody can help me with this and please have in mind that I try to learn jQuery (beginner at coding).
Thanks alot.
If i understand you correctly you are loading <script> tags into content and wish for it to execute? If so call this function i made a while back after insertion.
/**
*This function is supposed to execute script after script insertions
*/
function execute(){
$('#content script').each(function() {
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.setAttribute('async', 'true');
/**
*IEFIX (IE does not support .innerHTML on createElement)
**/
if(!_script.innerHTML){
_script.text=$(this).html().replace('\\\\',"\\");
}else{
_script.innerHTML = $(this).html().replace('\\\\',"\\");
}
document.body.appendChild(_script);
});
}
I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div>.
I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help
<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>
The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.
$('myelement').load('page.html #content', function() {
...
});
Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.
In you example, you would do:
$("#contentspace").load(this.href + ' #content', function(response){
...
});
Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.
I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>