Why does this javascript run locally but not on a web server? - javascript

I have the following Javascript/jQuery on my page:
<script>
$("#mymarkdown").load("./LPInfo.md");
var md = markdown.toHTML($("#mymarkdown").html());
$("#mymarkdown").html(md);
</script>
That page is here:
http://www.nickhodges.com/LeanTed/bootstrap/about.html
The page uses bootstrap. I've looked and see no errors in the console when rendering the code.
As you can see, it is not doing what I want, which is using markdown.js to render the contents of a file into HTML.
Here's the weird part, and the root of my question:
If I open the page as a local file, Chrome does nothing. IE9 will open and properly render the page, but only after I give permission to run the script.
Both browsers fail to render the page correctly using the above link. Firefox has the same result.
I confess to being pretty much of a n00b on all this, but I'm at a loss to explain the inconsistent behavior. I understand that the code is accessing a local file, but that shouldn't be a problem when accessed via the web server, right?
Anyway, and help will be appreciated.
UPDATE:
Here's the code for the page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>LeanTed Markdown Editor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../assets/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">LeanTed Markdown Editor</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li>Home</li>
<li class="active">About</li>
<li>Contact</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<div id="mymarkdown"></div>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
<script src="markdown.js"></script>
<script>
$("#mymarkdown").load("./LPInfo.md");
var md = markdown.toHTML($("#mymarkdown").html());
$("#mymarkdown").html(md);
</script>
</body>
</html>

The problem is that you're trying to run markdown.toHTML on the contents of #mymarkdown before it has fully loaded into the DOM (load being asynchronous). Use the "complete" callback of load and it works:
$("#mymarkdown").load("./LPInfo.md", function() {
var md = markdown.toHTML($("#mymarkdown").html());
$("#mymarkdown").html(md);
});
(The reason it works locally is probably because lpinfo.md is loaded near-instantaneously, either because 1. an Ajax call to the localhost is extremely fast, or 2. your browser already has the file from localhost cached.)

Do it like so:
$(function () {
$.get( './LPInfo.md', function ( data ) {
$( '#mymarkdown' ).html( markdown.toHTML( data ) );
});
});
So, the code is inside a DOMContentLoaded handler to make sure that the DOM is ready (since you're injecting content into it). Also, $.get is the appropriate retrieval mechanism here. You're doing a .load() which doesn't make much sense in your situation.
What you're doing with .load():
getting the MD file via Ajax,
inserting its contents into the DOM,
retrieving that content from the DOM,
processing the content with Markdown,
inserting the resulting HTML source code into the DOM.
What my code is doing:
getting the MD file via Ajax,
processing its contents with Markdown,
inserting the resulting HTML source code into the DOM.

Have a look at this or that question on how to enable local file system access via XHR.
Your actual problem is that .load() does only start the asynchronous load of the file. But even before it is loaded, you get the HTML content (likely empty?) and render it as markdown. Soon after, the element will get overwritten from the ajax callback. Use the callback parameter!
And don't use load at all if you are not loading HTML. jQuery has a powerful ajax function on which you even could set up a Markdown2html converter which is automatically used when a markdown file is served and html is wanted:
$.ajaxSetup({
accepts: {
"markdown": "text/x-markdown" // MIME type
},
contents: {
"markdown": /markdown/ // MIME type matcher
},
converters: {
"markdown html": markdown.toHTML
}
});
But for your purpose, just use a simple .ajax call:
$.ajax("./LPInfo.md").done(function(md) {
$(function() {
$("#mymarkdown").html(markdown.toHTML(md));
});
});

Related

Can't get javascript, JQuery to work with my PHP

Really nooby question, but couldn't find it on this site, and just can't get it to work.
How can I get javascript and jquery to work when putting CDN into headers / footers?
My javascript is working when I include the CDN and the tags right in with the HTML, but I want to have my javascript on other pages, rather than in with the HTML view pages.
I can't see what is wrong. Maybe you can help?
this is working
<div class="form-group">
<label for="caption">Event Description</label>
<script src="https://cdn.ckeditor.com/ckeditor5/12.3.1/classic/ckeditor.js"></script>
<textarea class="form-control" name="event_description" id="body" cols="30" rows="20"></textarea>
<script>
ClassicEditor
.create( document.querySelector( '#body' ) )
.catch( error => {
console.error( error );
} );
</script>
</div>
However this is not
I have
<?php require_once("includes/header.php"); ?>
<?php require_once("includes/footer.php"); ?>
on all tops and bottom of HTML view pages.
Here are my headers and footers
<?php ob_start(); ?>
<?php require_once("init.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin - Bootstrap Admin Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
footer
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="js/scripts.js"></script>
<!-- Bootstrap Core JavaScript -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- WYSIWYG -->
<script src="https://cdn.ckeditor.com/ckeditor5/12.1.0/classic/ckeditor.js"></script>
</body>
</html>
here is the scripts.js page
ClassicEditor
.create( document.querySelector( '#body' ) )
.catch( error => {
console.error( error );
} );
$(document).ready(function(){
alert('hello');
});
not sure why nothing works from the scripts.js page. The alert is not working. I have JQuery.js referenced also..
Thank you
You should put <script src="js/scripts.js"></script> after JQuery and other dependencies. Because your script.js is using JQuery before you imported it.
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- WYSIWYG -->
<script src="https://cdn.ckeditor.com/ckeditor5/12.1.0/classic/ckeditor.js"></script>
<!-- MY JS -->
<script src="js/scripts.js"></script>
</body>
</html>
Just make the following changes in your footer and everything will work fine.
Regarding to keep JS in header and footer
<script>-tag over the closing </body>-Tag, this will prevent that the page is loading endless for the Javascript file, before the page is actually loaded.
It was trends before to put JavaScript code in the header but now because of SEO and site performance, it is better to put JavaScripts in the footer. yes, that means all the js code.
How to avoid such issues in future?
you first need to include the dependencies required by your code and other libraries. like jQuery is required by most of the libraries bootstraps, fancybox, jQuery full calendar and so on. so first include jQuery library then other js libraries if they have any other dependencies than include them before your custom javascript. it is just same as in your code you define something above. what if you try to use it before defining it? no way it will never work...
Now what about CSS dependencies?
always include them in the header inside tags.

Cannot use jQuery in Laravel Blade file

I am trying to define my page specific Javascript in my blade file by defining a separate section for it in the file. I can add the same jQuery code in the app.js file and it works without issue, but when I put it in the blade file I get an error of
Uncaught ReferenceError: $ is not defined
Layout file - app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<script src="{{ asset('js/app.js') }}" defer></script>
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body class="fixed-nav sticky-footer bg-dark" id="page-top">
<!-- Navigation-->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav">
<!-- Nav Stuff -->
</nav>
<!-- End Navigation -->
<!-- Body -->
<div class="content-wrapper">
<div class="container-fluid">
#yield('content')
</div>
<footer class="sticky-footer">
<!-- footer stuff -->
</footer>
</div>
#yield('script')
</body>
</html>
Content Page - page1.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<!-- Page Stuff -->
</div>
#endsection
#section('script')
<script>
$(document).ready(function()
{
alert('hello world');
});
</script>
#endsection
I would prefer not to put all of my Javascript in the single app.js file, I would like to be able to use this section fine. Straight Javascript works fine here, but the jQuery does not.
edit:
Here is the app.js file that includes the jQuery library.
require('jquery');
require('./bootstrap');
require('jquery-easing');
// Administration Controller - Add System Type -> This code works just fine.
var numSysDataRows = 5;
$('#add-customer-information').click(function()
{
$('#system-customer-information').append('<div class="form-group"><label for="col'+numSysDataRows+'">System Data:</label><input type="text" name="col[]" id="col'+numSysDataRows+'" class="form-control" /></div>');
numSysDataRows++;
});
If I look at the source code and check the app.js file from the web server, I do see that jQuery is loaded into the app.js file.
Laravel loads jQuery by default, so it will be there unless you removed it from your complied app.js (running an npm commands to compile from your assets). The issue is that you are deferring this script. jQuery is being loaded after the page JavaScript is run.
Try removing the defer command.
If that doesn't work, see if jQuery is in your app.js file. If not, use a cdn or copy it to your public folder.
You don't need to remove "defer" from <script src="{{ asset('js/app.js') }}" defer></script>.
Paste jquery script tags below app.js then,
install npm
remove vue template in resouces/js/app.js
type "npm run dev" and hit enter
repeat #3 2 times
Then no Uncaught ReferenceError: $ is not defined will appear
NPM
Yes, I added jquery script tags
Jquery script tags
Remember that in the case that you are using the jquery CDN, you can try to put it in your head tag, I had that same problem and I have been able to solve it this way
I don't see you add file bootstrap and jquery. Have you added jQuery and Bootstrap file yet?
If not you can see in here : jquery Bootstap

FullCalendar displaying without css or any errors

So I'm trying to get full calendar installed on my website, and after a few issues, I managed to get to a point where I have no errors but the calendar itself isn't displaying correctly (like it doesn't have css).
I checked, and as far as I can tell, all of the files that need to be referenced are.
Any help would be greatly appreciated!
<!DOCTYPE html><head> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="src/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- FullCalender files references -->
<script src="src/jquery.js"></script>
<script src='src/moment.min.js'></script>
<script src='src/fullcalendar.min.js'></script>
<script src="src/gcal.js"></script>
<!-- Custom styles for this template -->
<link href="components/style.css" rel="stylesheet">
<link src="src/fullcalendar.min.css" rel="stylesheet">
<link src="src/fullcalendar.print.css" rel="stylesheet">ipt>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
googleCalendarApiKey: 'KEY',
events: {
googleCalendarId: 'ID#group.calendar.google.com'
}
});
});
</script><title>Western PA ARML</title></head> <nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Western PA ARML</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<!--<li>Home</li> -->
<li>Calendar</li>
<li>Join the Team</li>
<li>People</li>
<li>Archive</li>
<li>Links</li>
<li>About</li>
<!--<li>Photos</li>-->
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<body>
<div id="content"><div class="section">
<h1>Calendar</h1>
<div id='calendar'></div>
</div> </div> <!--Content-->
<div class="footer">
Ⓒ 2017 Western Pennsylvania ARML Team
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="src/bootstrap/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>-->
</body>
</html>
This is how it looks -
A few things which are issues with your code (starting from the original edit up to the current version):
1) You need to make sure your CSS and JS files are all based on the same version of fullCalendar, and also that your jQuery and momentJS files are compatible versions, and loaded in the correct order (see https://fullcalendar.io/support/ and https://fullcalendar.io/docs/usage/ respectively).
2) Don't use fullCalendar.io as a CDN. Either use the recommended CDNJS site (as per https://fullcalendar.io/download/) or download and host the files yourself.
3) <script>window.jQuery || document.write('<script src="src/jquery.js"><\/script>')</script> seems to be redundant, since you already included jQuery just above.
4) gcal.js needs to be loaded after fullCalendar.js, because it depends on it in order to work properly.
5) I realised your <link> tags are specified incorrectly. You need to put the URL in a "href" attribute, not a "src" (that's used for script tags). See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link fpr the spec.
6) You're loading the "print" CSS and the regular CSS both into the code, but the "print" style will override the regular style (because it's loaded later). You need to put a media query in the "print" one to ensure it only gets used when the user tries to print the page. e.g.
<link href="src/fullcalendar.print.css" rel="stylesheet" media="print">
Additional side comments:
1) You don't need jQuery-UI for this to work, and nothing else on your page seems to make use of it, so you can remove it.
2) You have HTML which is outside both the <head> and <body> tags. This is not valid. Anything you want to display should be inside <body>. Many browsers might be tolerant of this problem but it's messy and technically invalid HTML, so you can't expect it to always work properly.
You're placing your css in the wrong place.
<link href="components/style.css" rel="stylesheet">
<link src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.2/fullcalendar.min.css" rel="stylesheet">
<link src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.2/fullcalendar.print.css" rel="stylesheet">
Placing the code like this will cause external css resources to override your custom css.
Instead place it like this:
<link src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.2/fullcalendar.min.css" rel="stylesheet">
<link src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.2/fullcalendar.print.css" rel="stylesheet">
<link href="components/style.css" rel="stylesheet">

How to include javascript in html5

I can not connect an external JavaScript file to my html page.
When I put the script in the page with the tag it all works
but when I insert it in an external file is not working, what is wrong?
<!DOCTYPE!>
<head>
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<!-- JQuery da Google -->
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!---------------------->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<!-- CSS -->
<link href="style.css" rel="stylesheet" type="text/css" />
<!-- JS-->
<script src="js/function.js" type="text/javascript"></script>
</head>
<body>
<footer>
<img class="info" src="img/newsletter.png" width="32" height="32" alt="info" />
</footer>
<div id="info">
<ul class="infomenu">
<li class="newsletter">NEWSLETTER</li>
<li>PRIVACY</li>
<li>CONTACT</li>
<li>FOLLOW US</li>
</ul>
</div>
</body>
</html>
Javascript
//Jquery Info
$(document).ready(function(){
$(".info").hover(function(){
$("#info").fadeIn("slow");
});
$(".close").click(function(){
$("#info").fadeOut("slow");
});
});
You really messed up your html code, try googling for the HTML(5) basics, first of you should learn the basic construction of it like following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8">
<title>Welcome</title>
<link type="text/css" href="styles/default.css">
</head>
<body>
<!-- HTML Content -->
<script type="text/javascript" src=".."></script>
<script>
// Javascript inside this file
</script>
</body>
</html>
The link- and script part is not necessary, but you mostly will need it so I put it in the right order in.
Try putting script-Tags over the closing </body>-Tag, this will prevent that the page is loading endless for the Javascript file, before the page is actually loaded.
This way the external Javascript should work, also if you working localy, you should use a Webserver software like XAMPP. If you use XAMPP, after installing it, you have to start the Apache Service and then you work inside (if you didn't changed the path) the C:\xampp\htdocs folder. If you create a folder inside it called testing and place your index.php inside it, you just can type following in the browser http://localhost/testing and it will search for a index. html or php file and parse it.
If you just double click the file, you mostly will end up with security issues, which will prevent your code will work like you intended to do. You know that you double clicked a file if it starts like file:// and not http://.
But like I said, google for tutorials from the scratch. It takes time, but you can't do it without taking the time. Trust me, I do this for over 7 Years now and I am online nearly everyday and learning, learning, reading, testing, coding, learning, reading, testing and I STILL think that this is less than 5% of knowledge what I could learn.. never think you are at the end or near to it.. you never are, there are always things to learn and if you keep in thought that you are near the end, you will stop improving and never become good.
<script>
$(document).ready(function(){
$(".info").hover(function(){
$("#info").fadeIn("slow");
});
$(".close").click(function(){
$("#info").fadeOut("slow");
});
});
</script>

loading javascript in Ajax loaded page

i shall state my problem here.. I have an index.html page which has a prettyPhoto.js script in it. i have some menu links on my index.html. say one of these is "video gallery" now i load video gallery through Ajax and it loads fine. but the problem is i cannot get prettyPhoto.js to work in the external loaded file. Does anyone know how to do this?
Index.html looks like this (please note i have removed unnecessary code to make it readable)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>The Footy Lounge</title>
<!-- Scripts -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" language="javascript">
function loadXMLDoc(url,containerid){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200|| window.location.href.indexOf("http")==-1)
{
document.getElementById(containerid).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET',url,true);
xmlhttp.send();
}
</script>
<!-- End Scripts -->
<!--Stylesheets-->
<link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<link rel="stylesheet" href="css/articles.css" type="text/css" media="all" />
<!--[if lte IE 6]><link rel="stylesheet" href="css/ie6.css" type="text/css" media="all" /><![endif]-->
<!-- End Stylesheets-->
</head>
<body>
<div id="navigation">
<div class="cl"> </div>
<p align="right"><ul>
<li>news & events</li>
<li>photo gallery</li>
<li>video gallery</li>
<li>community</li>
<li>schedules</li>
</ul></p>
</div>
<div id="mainPage">
</div>
<!-- this is required for prettyPhoto to work -->
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
});
</script>
</body>
video_gallery.html looks like this
<!-- tried adding this, didn't work -->
<!-- <script src="../js/jquery.prettyPhoto.js" type="text/javascript"></script> -->
<div class="article-box">
Image test
</div>
<!-- I tried adding this, it didnt work -->
<!-- <script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
});
</script> -->
I am obviously doing something wrong here. And i can't find any answers on Google because i don't have a clue as to what to search for. i tried searching for "loading JavaScript in ajax page" and all the possible variants i could think of.
EDIT:
Ok i got it working. thanks to the people who answered.
here is code.
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#video_gallery").click(function(){
$("#mainPage").load('ajaxfiles/video_gallery.html',function (text, statusText){
if (statusText === "success")
{
$("a[rel^='prettyPhoto']").prettyPhoto();
<!-- target.find("a[rel^='prettyPhoto']").prettyPhoto(); --> //this didnt work for me so i used the above one. firebug gave me some error about target.find
}
});
});
});
</script>
As haynar mentioned, the content is loaded after prettyPhoto has been initialised. To work around this problem, you need to call the prettyPhoto initialisation function after loading the new content.
To make your life a whole lot easier (and your code a whole lot neater), change your loadXMLDoc function to take advantage of jQuery's built-in AJAX utilities, namely load():
function loadContent (url, container) { // remember, you're not loading XML
var target = $(container);
target.load(url, function (text, statusText) {
if (statusText === "success") {
target.find("a[rel^='prettyPhoto']").prettyPhoto();
}
});
}
load automatically inserts the HTML into the container for you, and the callback function in the code runs and initializes prettyPhoto for any new elements that have been added to the document.
Don't forget to change references to loadXMLDoc to loadContent, the latter is a better name since you're not actually loading an XML document.
The document ready has already occured, so it is not possible to call it again, just remove the $(document).ready(), but keep the $("a[rel^='prettyPhoto']").prettyPhoto();
If I am right, your Javascript does get loaded when you add it as a script tag (without commenting it out).
So the result wil be:
<script src="../js/jquery.prettyPhoto.js" type="text/javascript"></script>
<div class="article-box">
Image test
</div>
<script type="text/javascript" charset="utf-8">
$("a[rel^='prettyPhoto']").prettyPhoto();
</script>
I can explain you the reason why it doesn't work, but can't help you with coding 'cause I'm not familiar with that JS lib. JS lib run when page loads only ones, so when after it you're creating new objects it can't determine the new once to bind appropriate events and effects to them. You need to run your gallery initialization function one more time after loading new gallery items.

Categories

Resources