Loading an external .htm file into a div with javascript - javascript

So I got this code
Javascript:
<script type="text/javascript">
$(function(){
$('.ajax') .click(function(e){
e.preventDefault()
$('#content').load( 'file.htm' )
})
})
</script>
html:
Link
it works perfectly in firefox, but nothing happens when I click the link in chrome and IE simply opens a new window with the file. any advice?

I am not a coder of any sort, and I know there is more than one way to make this work.
This is what worked for me for MY situation.
I had a working site but with A LOT of code / DIV content all in one page and I wanted to clean that up.
I hope this Helps someone else!
I have been searching for this solution for quite some time and I have run across many examples of how it can work in different instances.
My scenario was as follows:
I have a photography website that uses a series of DIV tags containing the various "pages" so to speak of the site.
These were all set as:
<div id="DivId" style="display:none"></div>
The following script in the head of the page:
$(document).ready(function(){
$('a').click(function () {
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});
});
</script>
and called using the anchor links like this:
HOME
Where name was the name of the DIV to be called.
Please note the DIV will be called inside the parent container DIV.
Lastly and most importantly for this particular question and scenario, the DIV were all placed on the page as shown above.
Each div content was created just as if it were within the DIV tags but minus the opening and closing DIV tags and then saved as a separate .txt file, and called by placing this is the head of the parent page:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js">
and
$(document).ready(function() { // this runs as soon as the page is ready (DOM is loaded)
$("#DivName") // selecting "div" (you can also select the element by its id or class like in css )
.load("PathToFile.txt");// load in the file specified
$("#AnotherDiv").load("AnotherFile.txt");// Additional DIV can be added to populate DIVs on th eparent page.
});

Change the link to href="#" or "javascript:void(0);return false;"
<a class='ajax' href='#'>...</a>
The loading logic is all in your ajax call. But, you have also a link which points to the file, too.
So, it seems that some browsers give different priorities on how the click is handled.
Anyway, links that do something other than changing page (f.ex. executing js) shouldn't have an explicit HREF attribute other than something that "does nothing" (like above)

I believe the problem is that the script loads before the document is loaded.
try this:
$(document).ready(function (){
$('.ajax').click(function(e){
e.preventDefault()
$('#content').load( 'file.htm' )
});
});
I am not sure, but i can not see any other problem.

Related

jQuery : delete a page

I'm using jQuery mobile and my page is generated from an index.php file. When I click on links referring to another option of my php file (index.php?action=other_action) it loads in Ajax so the previous content is still kept in the code. This causes problems as nothing is dynamic anymore, because I'm using specific ids, so it breaks everything. Of course disabling Ajax works but I loose all the beauty of jQuery Mobile.
I guess a solution would be to create an onclick function on the <a>, that will prevent the page from keeping the previous content or delete the old page.
So is there a way to keep using ajax in a way that it doesn't break my dynamic elements ?
You can see it in action here, you can filter names if everything's good. Then click on the top left panel and click something, notice what happens in the inspector...
Thanks for any help.
Hi you have missed enclosing the selector within qoutes...
your jQuery
$(document).ready(function() {
//bind a listener to "click" event on links with class "markviewed"
$('a.ui-btn-present').click(function(event) {
$('ul.listlist').listview('refresh');
$(#pageone).remove(); //<-- selector should be within quotes
// get ids from clicked <a>
var id = $(this).attr('data-id');
$(this).attr({
"class" : "ui-btn ui-btn-icon-notext-ok ui-icon-check ui-btn-a"
});
After much more research I wasn't looking in the right direction: the problem was that the listview had to be refreshed. So I created a new function
<script>
function refreshlist() {
$('.listlist').listview("refresh");
$('#pageone').remove();
};
</script>
And then I added onclick= "refreshlist()"to all my links and now it works.

Fade in different section with static header and footer using javascript?

i was wondering how to create a dynamic website where the page layout is as follows:
header, section, footer
The header and footer would always be static and when the user clicks a part of the nav e.g About Us (within the header) the section in the middle dynamically changes and fades in the About Us section.
I would like to use pure javascript if possible and without it being part server-side, I assume you would give the sections ID's and in the javascript "onClick" of the nav link, the one section would display:none and another section would display in replace of it.
I found a similar example on this website: http://www.templatemonster.com/demo/44858.html
What is the easiest way to create this effect? I have a VERY brief idea but how could you go about this?
If anyone could include a jsfiddle example, would be much apprieciated
What you are looking to do is called pjax. Pjax uses XML Http requests(ajax) to load a specific piece of content into a placeholder like you are trying to do.
Someone clicks to a new page.
Javascript requests this page from the server.
Once loaded, optionally fade out the old content.
Replace with the new content and optionally fade it in.
Use pushstate to add a state to the browser history. This allows the back and forward buttons to work.
Here is a pjax library that is handy for doing this easily across new and old browsers and has a good explanation:
https://github.com/defunkt/jquery-pjax
It would not be a good idea to include all of the content on one page with display:none because then it will still need to be downloaded by the browser even if the user never views it. Nevertheless, here is a JSfiddle showing this approach which is close to what you described:
http://jsfiddle.net/Tb4eQ/
//Wait for html to be loaded
$(document).ready(function(){
//Store reference to frame to load content into in a var, as well as the content to load in.
var $content = $('#div_1');
var $frame = $('#my_frame');
//Bind an event handler to the click event of something
$('#press').on('click', function(){
//fade out the frame, swap in the new content, and fade it back in.
$frame.fadeOut('fast', function(){
$frame.html($content.html()).fadeIn('fast');
})
});
});
You can use the jQuery method .load() which loads data from the server and place the returned HTML into the matched elements. Also the .toggle() method allows you display or hide elements.
Consider the following example: Suppose we have a page named index.html ...
<header>
<nav>
<ul><li id="nav-about">About us</li></ul>
</nav>
</header>
<section>
<article id="dynamic-viewer">
Dynamic content will be placed here!
</article>
</section>
<aside>
<div id="loader" style="display:none">
<img src="http://www.ajaxload.info/images/exemples/24.gif" />
</div>
</aside>
... and we have another file named about.html which is just a view:
<div>
<h2>About us</h2>
<p>This content is placed dynamically into #dynamic-viewer</p>
</div>
Now, I will load the content of about.html into the content wrapper in index.html using the jQuery.load() method.
//Click handler to load the "about" view
$(document).on("click.about", '#nav-about', function() {
fnShowLoading(true);
//Loads the content dynamically
$('#dynamic-viewer').load('views/about.html', function() {
fnShowLoading(false);
});
});
//Shows or hides the loading indicator
function fnShowLoading (show) {
$('#loader').toggle(!!show);
}
Actually, the only lines that matters here are:
//loads the content dynamically
$('#dynamic-viewer').load('views/about.html', function() { });
//shows or hides the loader section
$('#loader').toggle(!!show);
You could try to use Ajax calls to partially refresh parts of the page or just load the whole thing and let jQuery handle the hiding and showing of elements on click events.
http://www.w3schools.com/ajax/
http://api.jquery.com/hide/

Targeting links with jquery mobile

This is pretty much an add on to a question I posted before about loading an external page without ajax, but keeping it an iOS web app window. What I came up with for that example was this
<script>
$(document).bind('pageinit', function() {
$("#test").click(function (event) {
event.preventDefault();
window.location.assign("test.html");
});
});
</script>
But now what I want to do is to set this up for every link I would have on that page. Seeing as I don't know how many links I could have, it would be very tedious to do this every time I add a new link. So I found this snippet and thought I could combined the two some how, I just need some direction on how.
$('a').each(function(index){
var elementId=$(this). attr("id");
elementId='#'=elementId;
So for each a tag or href on my page, it will automatically grab the link and load it in that particular manner automatically.
Of course you can combine your codes. Anyway I haven't tried your code but you have to wrap an .each() function around your click events. Also you should give every clickable link a the same class. Should look like this:
$('.class').each(function(){
$(this).click(function(){
event.preventDefault();
window.location.assign("test.html");
})
});
if you now want those links to link on different pages you can define a data-href attribute on each link. like this: data-href="test2.html" in your html.
You can now use
$(this).data("href");
and put the output into a variable. Afterwards you can place it in your window.location.assign thing dynamically.
Hope I understood your problem and it helped.

Preloader does not preload and loads the page a second time

I found this nice jQuery preloader/progress bar, but I cannot get it to work as it is supposed to. The problem is that it first loads my page and after my whole page is loaded the 0%-100% bar displays quickly, after that it reloads my page again. So it does not show the progress bar BEFORE the page loads and it loads the page a second time as well.
Here is my implementation code:
<head>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="js/jquery.queryloader2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("body").queryLoader2();
});
</script>
</head>
<body>
My content...No other reference in here for the Jquery preloader
</body>
Thanks for any help in advance.
I could be very, very wrong here, but in my opinion:
The plugin is flawed.
You have some issue in your page that causes a redirect.
I have created a test fiddle and found out the following:
If there are no images on the page, then the plugin's private function completeImageLoading(); is never called because it is only bound to the image elements. When there are no images -> there's no binding -> no triggering -> nothing completes -> you stay with overlay 0% as demonstrated by the fiddle that is NOT RUN (jsfiddle doesn't see relative images when the page is not run).
The plugin doesn't take into consideration remote images. So if you declare them like so <img src="http://example.com/image.jpg"> - then it won't work because the plugin doesn't recognize them. In fact it is using $.ajax to load images which, obviously, generates a error when trying to access another domain.
The plugin doesn't reload the page (at least in Google Chrome)... check your console output while in the fiddle. It displays the message once per click on Run.
Suggestions:
Make sure you provide at least one relative or background image (though I haven't tested backgrounds...) for the plugin to work.
Show us more code. The fiddle demonstrates that the plugin does NOT cause page reload (at least in Chrome... are you using another browser?). It must be something you made that interferes here.
Specify some options for the plugin (behaves weird when there are none).
Edit regarding preloader
Regarding preloader... if displaying progress is not mandatory for you, then you can just use a window.onload trick. On DOM ready $(...) you create an opaque page overlay with a "Please wait..." message and some animation if you fancy it. Then you wait for window.onload event which "fires at the end of the document loading process... when all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading." When window.onload triggers, you just remove your overlay and voila - the page is ready!
Edit 2 regarding preloader
Actually, you don't even need $(...)... what the hell was I thinking? Just create your overlay (a simple div with a unique id) in your html, style it so that it fills the screen and give it a z-index:1337 CSS attribute so that it covers the entire page. Then, on window.onload:
window.onload = function () {
// Grab a reference to your overlay element:
var overlay = document.getElementById('myOverlay');
// Check if the overlay really exists
// and if it is really appended to the DOM,
// because if not - removeChild throws an error
if (overlay && overlay.parentNode && overlay.parentNode.nodeType === 1) {
// Remove overlay from DOM:
overlay.parentNode.removeChild(overlay);
// Now trash it to free some resources:
overlay = null;
}
};
Of course, it's not really a preloader, but simply an imitation.
Here's a working fiddle you can play with.
P.S. I personally don't appreciate preloaders, but that's just me...
Try out this(Remove the document.ready event and simply call this):-
<script type="text/javascript">
$("body").queryLoader2();
</script>

On hover open a DIV, DIV content should dynamically load from a separate URL

I'm sure someone has already done this and posted it online, but I'm having trouble finding such an example or tutorial.
Basically, I want to have a series of links on the page. If you hover your mouse on the link, it should open a drop down DIV box under the link and then load content into the DIV from a remote URL that is pre-defined.
Has anyone seen such an implementation or have any ideas on how to do it with jQuery?
I think you're looking for something similar to:
$(document).ready(function(){
$("a").hover(function(){ //When a given link (<a> tag) is hovered over
$("div").load(this.href).show(); //load the src of that tag into a given div container.
});
});
Here's a simple test in jsFiddle, but I didn't know what to put with the href...so all you'll see is the div appear with the post error...not very pretty, but if anyone has suggestions then I'm definitely open to all.
http://jsfiddle.net/ChaseWest/VEuH9/2/
I would go with something like the following. Note that we target only anchors who don't have the loaded class. The reason why is because we don't want to load the contents for any anchor multiple times. Whenever the user passes over an anchor, its content will be loaded and it will get a special class indicated this. If they pass over it again, nothing happens.
$("body").on("mouseenter", "a:not(.loaded)", function(e){
$(".mydiv").load(e.target.href, function(){
$(e.target).addClass("loaded");
});
});

Categories