I changed the menu on my website so it replaces the main content on my page with html files using jquery instead of just href-ing the html pages. Something like:
$(function() {
$('.new_page_title').on('click', function (e) {
e.preventDefault();
$('.main_content').load('new_page.html');
$('body').scrollTop(0);
});
});
For one of my pages I want to have a rotating sentence that gets randomly chosen from an array. Before, I was just doing it on page load, but now I have added a line to the above function to call the randomizer which looks like:
function make_a_sentence() {
var sentenceArray = [
'digging holes in the back yard',
'eating our vegetables',
'doing something important',
'building the future',
'watering my plants',
'propogating succulents',
'watching Call the Midwife',
'looking outside and dreaming of salvation',
'poopin\'',
'providing for my family',
'watching you through your window',
'digging around craigslist',
'rotating my tires',
'settling lawsuits'
];
var selected = Math.floor(sentenceArray.length * Math.random());
$("#id_of_div").html(sentenceArray[selected]);
}
And then calling make_a_sentence() at the end of the click function. When I just load the page, the sentence doesn't show up, and when I debug it inserts the sentence into the div until it gets to the end of the debug and then the sentence disappears. Any ideas?
The load function is asynchronous, you need to run code dependent on the loaded page's content in load's callback (otherwise your changes gets rewritten as they occur before the load is completed), like:
$(function() {
$('.new_page_title').on('click', function (e) {
e.preventDefault();
$('.main_content').load('new_page.html', function () {
$('body').scrollTop(0);
make_a_sentence()
});
});
});
See jQuery.load for reference.
Related
I am trying to set the margin-left of a specific div (let's call it: div1) to be:
-1 * $('.div2 canvas').width()/2
So I am using the following line of code to do that:
$('#div1').css('margin-left', -1 * $('.div2 canvas').width()/2);
Once the page is loaded the result it gives me is -150. However, if I run the same exact line of code in the Chrome console, it gives the right result: -360 since the total width of div2 is 720.
I tried adding:
$(window).load(function () { });
or
$('#div1').load(function () { });
or
$('.div2 canvas').load(function () { });
but that did not help.
My assumption is that the width of div2 is changing based on some sort of information that is being injected and that once the page is ready the total width of the div 720px (in this example) but I am not entirely sure how to run this line of code once the whole page has been loaded and everything has been injected.
$(window).load(function () { });
should have helped. You also might try
$(document).ready(function () { });
but if that doesn't help, you'll need to show us your page (or a demo containing the problem) and the code which injects things after that.
You'll want to wrap this code in a document ready callback.
$(document).ready(function () {
// Your code
}
This ensures that the html is loaded, however it does not care about loaded images, which is where .load comes in. If your div contains image tags, you'll need two callbacks.
$(document).ready(function () { // Ensures that your document is loaded
$('.div2 canvas').load(function () { // Ensures that the images within our tag are loaded
// Your code
}
}
If we do not enclose this second callback definition in document ready, the tag we're referring to $('.div2 canvas') will not exist, and thus no load callback will be bound.
Am currently using head.js to defer loading of js files for my website. Am using colorbox in my project. The problem is that at times, the colorbox doesnt fully load (it opens the colorbox in a new page rather than in a dialog), but when i do several refreshes, it finally loads.
I guess it might be that the page content that is meant to open the colorbox dialog gets loaded even before colorbox js files are fully loaded by head.js. Is this the actual cause?
I would want to have colorbox display correctly each time without need for a refresh.
How do I keep the colorbox page code to execute only after head.js finishes loading all its dependent files?
thanks. nikk
Put your colorbox html code in a div.
<div id="colorBoxDiv" style="display:none;">
</div>
In the last line of head.js, add this code:
$("#colorBoxDiv").html($("#colorBoxDiv").html()).show();
head.js had a lot of different options how to do that. you can run callback function when needed files loaded, or use test feature api call.
For example:
// queue scripts and fire a callback when loading is finished
head.load("file1.js", "file2.js", function() {
// do something
});
// same as above, but pass files in as an Array
head.load(["file1.js", "file2.js"], function() {
// do something
});
// you can also give scripts a name (label)
head.load({ label1: "file1.js" }, { label2: "file2.js" }, function() {
// do something
});
// same as above, but pass files in as an Array
head.load([{ label1: "file1.js" }, { label2: "file2.js" }], function() {
// do something
});
// Labels are usually used in conjuntion with: head.ready()
head.ready("label1", function() {
// do something
});
// Actually if no label is supplied, internally the filename is used for the label
head.ready("file1.js", function() {
// do something
});
More in documentation
Strange behavior of JavaScript with jQuery Address (plugin).
I have this code:
var handler = function(data) {
$('#conteudo').hide().html($('#conteudo', data).html()).fadeIn(500);
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
};
And it works. Perfectly.
Now I change the code:
var handler = function(data) {
$('#conteudo').fadeOut(500, function() {
$('#conteudo').html($('#conteudo', data).html()).fadeIn(500);
});
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
};
Now the fade out effect works, and after fade in (with new content). Beautiful! But this little change in the way of writing the new content (inside of the new function, after fadeOut) broke my sub-links inside my pages.
Here's a live example:
Access this URL: http://impulse.im/clean/2/
In the top menu, click on 'Contato'.
Now look the href of link 'Rafa' in the loaded content!
http://impulse.im/clean/2?_escaped_fragment_=%2Fcontato%2Frafa.
This is not correct: it should read
http://impulse.im/clean/2/#!/contato/rafa
Again: http://impulse.im/clean/2/ - Click on 'Contato'. Now RELOAD the page.
The link 'Rafa' is now correct.
What this new function (after fadeOut) is doing with the code? Why this function is breaking my link?
Thanks!
The problem is that you are calling the address plugin before the html stored in data is actually placed on the page. It happens because you call the $('#conteudo').html($('#conteudo', data).html()).fadeIn(500) asynchronously as it's called as a callback to the fadeOut method.
Change it this way:
var handler = function(data) {
$('#conteudo').fadeOut(500, function() {
$('#conteudo').html($('#conteudo', data).html()).fadeIn(500);
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
});
};
This will call your address plugin after the new content was placed in the page.
Before it worked like this.
handler returns data -> content fades out -> you call the address plugin but the content isn't placed on the page yet -> after 500ms you the callback adding the content is called.
Now it'll be like this.
handler returns data -> content fades out -> after 500ms the content is added and the address plugin is called
I am struggling with jQuery for a long time now. It is very powerful and there are lot of great things we can do with jQuery.
My problem is that I use a lot of jQuery features at the same time. E.g. I have a site that displays items, 12 items per page and I can paginate through the pages using jQuery. On the same page I implemented a thumpsUp button that uses jQuery too.
The more jQuery features I use, the harder it gets to arrange them properly. E.g.:
$(document).ready(function() {
$(".cornerize").corner("5px"); //cornerize links
$('a#verd').live('click', exSite); //open iframe
$("a.tp").live('click', thumpsUp); //thumps up
$("a#next").click(getProgramms); //next page
$("a#previous").click(getProgramms); //previous page
//for the current page reload the content
$("a#page").each(function() {
$(this).click(getProgramms);
});
//this isn't working...
$('.smallerpost').live('click', alert('test'));
});
Have a look at the last code line. I want to perform an alert when the div element is clicked. Instead of doing so the page shows me the alert when I refresh the page. A click on the div has no effect.
What am I doing wrong? What would be a strategy here to have clean and working jQuery?
Change that line to
$('.smallerpost').live('click', function () {
alert('test');
});
and while you're there...
$("a#page").each(function() {
$(this).click(getProgramms);
});
has exactly the same effect as:
$('a#page').click(getProgramms);
... but technically there should be only one element with id='page' anyway
Your code $('.smallerpost').live('click', alert('test')); calls the alert immediately and passes its return value into the live function as the second parameter. What you want to pass there is a function to call, so you want:
$('.smallerpost').live('click', function() {
alert('test');
});
or
$('.smallerpost').live('click', handleSmallerPostClick);
function handleSmallerPostClick() {
alert('test');
}
...depending on how you structure your code.
I'm loading remote data using dynamic script tags and JSON. the remote page that I'm displaying on my website has a div in it that I use to load content into.
The problem is the javascript functions do not see the div as the page loads because it is remote data. If I set a timeout of about 300, it usually works and my javascript can see the div. But sometimes it takes longer and it breaks the javascript.
I'm tring this:
function load_content() {
if (document.getElementById('remote_div') == null) {
setTimeout('load_content()', 300);
} else {
document.getElementById('remote_div').innerHTML = 'Content goes here'
}
}
but it just doesn't work. What am I doing wrong?
You may want to do this using setInterval. Something like:
var intrval = setInterval( function(){
if(document.getElementById('remote_div')) {
load_content();
clearInterval(intrval);
}, 50);
function load_content() {
//loading content here
}
This way you don't have to estimate the loading time. load_content is executed when div#remote_div can be found in the DOM tree.
Edited based on comments, forgot to assign the interval, so it wouldn't ever clear indeed.
Are you using iframe?
If so, try
document.getElementById('YOUR_IFRAME_ID').contentWindow.document.getElementById('remote_div')