Load Html Content if not exist JQuery AJAX - javascript

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .

Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.

In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.

try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});

I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)

You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});

Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

Related

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

Completely removing loaded forms with jQuery -

So I'm using .load() to load a view into an element - and when I'm done with it I do an .innerHTML = '' to get rid of it.
But if I do it more than once (i.e. close and open the element) - the form is definitely gone in between and reloaded, but when I submit it submits duplicates.
Here is the code:
$('a.comments').click(function(e){
e.preventDefault();
// $('.overlaybackground').addClass('open');
Component.Overlay.toggleOverlay();
$('#commentcontainer').load($(this).attr('href'), function(){
Component.Forms.init(page, {});
});
});
$('.overlaybackground').click(function(e){
if(e.target.className == 'overlaybackground open'){
e.preventDefault();
Component.Overlay.toggleOverlay();
// $('.overlaybackground').remove('*:not(#commentcontainer)');
document.getElementById('commentcontainer').innerHTML = '';
}
});
Not sure of the specific scenario. But if you only want to toggle the visual, simply toggle the CSS property display of the form instead of removing it from the DOM:
display:none<--> display:block
Try the following:
$('#commentcontainer').empty()

Trying To Add Onclick To Links, But Can't With .onclick

So I'm trying to use ajax to put content into a div, and trying to have it change all internal links before it adds the content so that they will use the funciton and load with ajax instead of navigating to another page. My function is supposed to get the data with ajax, change the href and onclick attributes of the link, then put it into the div... However, all it's doing is changing the href and not adding an onclick attribute at all. Here's what I was using so far:
function loadHTML(url, destination) {
$.get(url, function(data){
html = $(data);
$('a', html).each(function(){
if ( $.isUrlInternal( this.href )){
this.onclick = loadHTML(this.href,"forum_frame"); // I've tried using both a string and just putting the function here, neither seem to work.
this.href = "javascript:void(0)";
}
});
$(destination).html(html);
});
};
Also, I'm using jquery-urlinternal. Just thought that was relevant.
You can get the effect you want with less effort by doing this on your destination element ahead of time:
$(destination).on("click", "A", function(e) {
if ($.isUrlInternal(this.href)) {
e.preventDefault();
loadHTML(this.href, "forum_frame");
}
});
Now any <a> that ends up inside the destination container will be handled automatically, even content added in the future by DOM manipulations.
When setting a function to onclick through js it will not show on the markup as an attribute. However in this case it is not working because the function is not being set correctly. Easy approach to make it work,
....
var theHref=this.href;
this.onclick = function(){loadHTML(theHref,"forum_frame");}
....
simple demo http://jsbin.com/culoviro/1/edit

how to create onclick for a link

i have a div for which i set value dynamically during run time, if there is value than i have enable or create a link which will have onclick method where i will call a javascript method.
how to do this in jquery or javascript?
I set value to a div like the following,
document.getElementById('attachmentName').innerHTML=projectInforamtionMap.Cim_AttachmentNames;
this the div :
<tr>
<td align="left"><div id="attachmentName"> </div></td>
</tr>
Kindly help me to find and fix.
Best Regards
You can set a onclick function:
document.getElementById('attachmentName').onclick = function() {};
Assume that your function are previously define like this
function foo(){alert('function call');}
After adding innerHTML
In Javascript
document.getElementById('attachmentName').setAttribute('onclick','foo()');
In Jquery
$("#attachmentName").attr('onclick','foo()');
You have several alternatives
JavaScript:
// var elem = document.getElementById('attachmentName');
elem.onclick = function() {};
elem.setAttribute('onclick','foo()');
elem.addEventListener('onclick', foo, false); // The most appropiate way
jQuery:
// var elem = $('#attachmentName');
elem.click(foo);
elem.on('click', foo);
$('body').on('click', elem, foo);
Between the 3 jQuery alternatives, the last is the best one. The reason is due to the fact that you are attaching an event just the body element. In this case, it does not matter but in other cases, you are probably willing to attach the same event to a collection of elements, not just one.
Therefore, using this approach, the event is attached to the body but works for the elements clicked, instead of attaching the same event to every element, so it's more efficient :)
$('#attachmentName').click(function(){
//do your stuff
})
jquery way:
$("#attachmentName").click(function() {
some_js_method();
});
You can do this without inserting link in the div in following way
document.getElementById("attachmentName").onClick = function () {
alert(1); // To test the click
};
You can achieve it with the help of jQuery as well in the following way.
$("#attachmentName").click(function ()
{
alert(1);
});
for this you have to include jQuery liabray on the page. refer jQuery.com
Still if you forecefully want to include the link in Div then following is the code for it
var link = $("<a>"+ $("#attachmentName").text() +"</a>");
$("#attachmentName").html($(link);
link.click(function () {
alert(1);
});
Hope this would help.
as i was converting a classical asp details page to a one-page ajaxified page, i converted the existing links in the page to get the details loaded in the DIV in the same page. i renamed the href tag to dtlLink and got that data in the jquery load() function.
detail.asp (server.urlencode is added and required here )
<a href=""#"" onclick=""javascript:LoadDetails(this)"" dtllink="detail.asp?x=" & Server.URLEncode(Request("x"))&y=" & Server.URLEncode(Request("y")) > link text </a>
parent.asp (it has some extra code for holdon.js spinner image, button enable/disable, results div show/hide)
Jquery
function LoadDetails(href) {
//get the hyperlink element's attribute and load it to the results div.
var a_href = $(href).attr('dtllink');
console.log(a_href);
$('#divResults').html('');
DisplayHoldOn();
$('#divResults').load(a_href, function (response, status, xhr) {
$('#divCriteria').hide();
HoldOn.close();
if (status == "error") {
var msg = "There was an error: ";
$("#divResults").html(msg + xhr.status + " " + xhr.statusText);
$('#divCriteria').show();
$("#cmdSubmit").removeAttr('disabled');
}
});
}

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

Categories

Resources