If true, execute the rest of jQuery - javascript

I've got a jQuery file, some of which determines the layout and some of which determines events to be clicked later.
The code that determines the layout, I can't put in a CSS file because it's dependent on the .width() of some elements — so I'm stuck with JS for now.
What's the best way to make sure these layout changes happen first, and if so, run the rest of the file? Here is an example of the code which determines the layout:
archive.css({left: archivePosition});
films.css({right: - filmsPosition});
index.css({left: (nw / 2) - (iw / 2) });
And is it worth me separating these into two different JS files?

Try this out:- http://jsfiddle.net/adiioo7/6xSC5/
JS:-
jQuery(function($){
$("#test").width(function(index, width){
if(width)
{
//your conditional code.
}
});
});

Related

jQuery remove twice function call

Please consider this very simplified sample.
Below code remove a fixed nav bar from pages when screen size is small. It is named removeFixedNavbar().
This should be done when document is loaded and when window is resized. Please see the code. Well, this code seems some how ugly (calling removeFixedNavbar() twice, is it a better way to write it (with less code).
$(document).ready(function() {
removeFixedNav();
$(window).resize(function(){
removeFixedNav();
});
});
$(document).ready(removeFixedNav);
$(window).resize(removeFixedNav);
This should work, but i think it should be doable using CSS Media Queries only (depends upon the use-case).
Even simpler could be:
$(function(){
$(window).resize(removeFixedNav).trigger("resize");
});
Placing it at bottom most part can get rid of $(function(){...})
An other equivalent version can be:
$(function(){
$(window).trigger("resize");
});
$(window).resize(removeFixedNav);
Well you call it twice in document.ready.
Place window. resize outside document.ready event.

jquery not quick enough to take effect

I have a need to add a class to certain pages - ones that contain an ID of #hero. For all other pages, the class must not be added.
Because I'm using asp.net with a few layered master pages, its not as simple as just adding a class directly to the html becuase the body tag sits a couple of pages above the aspx page.
I could locate the body tag, but so far I've tried to avoid that due to the added complexity, and instead tried to use jquery.
Here's the code:
$(document).ready(function () {
updateBodyClasses();
});
function updateBodyClasses() {
if($("#hero")) {
$("html, body").addClass("hero");
}
}
Nothing complicated, but here's the rub. By the time the class has been appended, the page has been rendered and the class doesn't seem to have any effect. However, if I test it by adding the class directly to the html, it works - so I know the CSS works and that its a timing issue.
I suppose I could add the code higher up the page - jquery is deferred, so I would need to know the equivalent javascript to try it out.
Would appreciate any thoughts on this potential solution, or perhaps and other ideas.
/* UPDATE */
For clarity, it seems to be the HTML related class that isn't being applied.
You can alter the DOM without waiting for it to be ready.
You need to:
load jQuery in a synchronous way(without defer or async).
Put #hero element i above the script.
Please consider this example:
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hero">I don't care about DOM being ready</div>
<script>
var $el = $('#hero');
if ($el.length) {
$el.addClass('red');
}
</script>
You can use IIFE(Immidiately Invocked Function Expression):
like:
(function()
{
if($("#hero")) {
$("html, body").addClass("hero");
}
})();
just put your function in document ready like
$(function(){
if($("#hero")) {
$("html, body").addClass("hero");
}
});
No real solution provided.
Not reasitic to change the whole site infrastructure - from one that defers jquery to loading it synchronously.
The two other jquery answers are as per the current setup and don't work.
The only working solution was provided by Tushar, although it would still require selective loading of the script, which was not included in the answer.
In the end, I used a workaround, which bypassed the need for any javascript. Instead of selectively adding a class to html tag, I added the css permanently to the html tag, affecting all pages. I then added an inner div, which reverses it out. This means that any page can now manipulate its own functionality directly without having to add classes to the html tag.

Conditionally serve javascript with Foundation Framework

I'm working with the Foundation Framework and I was wondering if there are any callbacks or functions that will deliver jQuery or javascript based on the current screen size or media query.
For example
if ('screen_size' =< 'small') {
// do some jquery
}
Not sure if this is possible.
Any Ideas?
I am not sure if there are any mixins for it, but you can manually load a script via jquery, based on the window width (maybe attach it to a resize event as well as to onload?)
if( $(window).width() <= 1024 ){
$.getScript("test.js", function(){
alert("Running test.js");
});
}
I really love the jRespond plugin. Very useful for this sort of thing.
https://github.com/ten1seven/jRespond

Using jQuery Infinite scroll plugin without pagination markup?

So I'm trying to implement the popular inifnite scroll plugin to replace my current home made infinite scroll script:
http://www.infinite-scroll.com/
&
https://github.com/paulirish/infinite-scroll
Anyway it seems like this plugin requires there to be html pagination on the page. Namely due to these options:
nextSelector: "div.navigation a:first",
navSelector: "div.navigation",
I don't have pagination markup on the page. I don't care if my site isn't compatible for crawlers/js disabled users.
So is there a way to implement this plugin without a physical html pagination?
In my custom script I was doing something like:
var $page = 1;
// Load content for $page
$page++;
Anything like this, i.e. I can pass in the starting page as an integer?
Take a look at this, very simplified version of infinite scroll, that doesn't require any pagination elements.
http://www.innovativephp.com/demo/infinitescroll/
You can create it easily with jQuery/javascript.
It's a bit hard to write a universal for anything now, but the main principle is this:
If you're loading latest content (newest first, older scrolled):
Load first set of elements (weather it be blogsposts, images, quotes) that takes a bit more than screen height. Keep the last item's ID in a variable.
use setInterval to detect if user scrolled the page, then load data that has lower ID than your last ID that you saved. Then keep saving last ID's and load new content.
Good luck!
Something like this:
function loadnewdata()
{
// do ajax stuff, update data.
}
setInterval(
function (){
if(($(document).height() - $(window).height() - $(document).scrollTop()) < 500){
loadnewdata();
}
},
500
);
You'd write the loadNewData() function for yourself, of course. Depends on your data.
This loads new data each 500 if the user has scrolled the page.

jQuery .load() does not load plug-ins [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a main page with 2 links that load external files via .load(). The first file has a simple JavaScript rollover, which works when the content is loaded. The second file has a jQuery plug-in that does not work when loaded via .load() - but works fine when the data file is viewed by itself.
Main file: http://gator1105.hostgator.com/~carc/test-load.html
Second data file that works by itself, but not from .load(): (same URL as above, but the file is test-load-two.html - StackOverflow will allow me to create only 1 hyperlink)
Rather than paste my source code here, you can just view it from the pages themselves.
How can I get the second file with the slideshow to work when loaded with .load()?
I acutally did something similar with a site I'm working on. What you'll want to do is make a callback function for each page for the $.load() call on the main page.
See the following code from the jquery.load() documenation:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your particular case, you'd want something like this on the main test-load.html page.
$(document).ready(
function(){
$('li').click(function(){
var showThisContent = this.id;
$('#content').load('test-load-'+showThisContent+'.html', function(){
if (showThisContent == "one"){
//Do logic for test-load-one.html
//Pre-load your images here.
//You may have to assign a class to your anchor tag
//and do something like:
$('a.assignedClass').mouseover(function(){});
$('a.assignedClass').mouseout(function(){});
} //end if
if (showThisContent =="two"){
//Do logic for test-load-two.html here
$('.slideshow').cycle({
fx: 'fade',
speed: 500,
timeout: 0,
next: '.nextSSimg',
prev: '.prevSSimg',
pager: '#SSnav',
cleartype: true,
cleartypeNoBg: true
}); //end .cycle()
} //end if
); //end .load(location, callback function())
}); //end $('li).click()
}); //end $(document).ready()
Now, obviously I didn't convert all your code, but what's happening here is that once document.ready is complete, the callback function will run, and since the elements like '.slideshow' are now loaded into the DOM, you're callback code will bind to them appropriately.
You could switch this code around in several ways to have the same result (i.e., wrap 2 $.load()s into conditions rather than doing the conditional logic in the .load callback, and/or put a callbackOne() and callbackTwo() function above document.ready and then call them appropriately) but that's your preference. You should be able to do what you want to using the callback function argument of the $.load().
Ignore this answer
Your second file does its initialization in a "document.ready" block. That's not going to be run when your content loads via AJAX. Try taking the code in the second page that's inside "document.ready" out of that, so that it's just a bare script block.
[edit] Oh I see - not only is the script inside a "document.ready" block (well, it's not anymore), but that second page is a complete HTML document. You can't really load a complete HTML document into the middle of another document; it doesn't make sense, and jQuery is only going to grab what's in the body. Thus, try moving your script tag into the body and see what happens. (You still don't want "document.ready", I don't think.)
[edit again] actually I take that back - I don't think jQuery strips anything out; I just bet the browser gets confused.
[edit yet again] ok, ok I see that you've changed it again - let me take a really close look.
OK here's a better answer: for reasons I don't understand, when you load a fragment (or a whole page; whatever) with jQuery using the special "selector" trick to pluck out just a portion of the document:
var showThisContent = this.id;
$('#content').load('test-load-' + showThisContent + '.html #content-area');
the jQuery library strips out the scripts completely from the content, and doesn't ever run them. Why? I don't know.
I know that you probably don't trust me anymore, but here's what I did with your source code: I took that second file (test-load-two) and stripped out the head and stuff; basically I made it a fragment containing only the "content-area". (I also got rid of the script tag that loads jquery, as you don't really need that since the outer page already has it.) Then I changed the main page (test-load) so that when it calls "load" it just passes in the URL without that '#content-area' selector. That works.
[edit] I just posted a question to the jQuery forum: http://forum.jquery.com/topic/the-load-function-and-script-blocks
Don't go for $.load. Try $.get instead, which might seem less comfortable, but it worked for me in a different case. Sample code as following.
$(li).click(function() {
// your code for finding the id
$.get('test-load-' + id + '.html', function(responseHtml){
$('div#content-area').empty().append($(responseHtml)); // remove all elements from #content-area
// $('...').html(responseHtml) will not work
});
});
I hope this solves your problem.

Categories