Rookie: window.onresize needed - javascript

I'm a rookie when it comes to programming, so I really need your help here. I need to change some code to fulfil my needs and I can't seem to do it in a proper way. What I need right now, is to take this script and make it work when the $(window).width > 480 . Also, I need this script to run every time the user resizes the window.
I apologise for my silly question, but I'm just starting to learn the basics about Javascript and Jquery, and I can't seem to find the answer to this question this time.
Here is the code
$(window).load(function(){
(function($) {
$.fn.eqHeights = function() {
var el = $(this);
if (el.length > 0 && !el.data('eqHeights')) {
$(window).bind('resize.eqHeights', function() {
el.eqHeights();
});
el.data('eqHeights', true);
}
return el.each(function() {
var curHighest = 0;
$(this).children().each(function() {
var el = $(this),
elHeight = el.height('auto').height();
if (elHeight > curHighest) {
curHighest = elHeight;
}
}).height(curHighest);
});
};
$('.articles_container').eqHeights();
}(jQuery));
});

The window has an .innerWidth property which I presume is still accessible through jQuery. so your code might be something like this:
$(window).resize(function() {
if($(window).innerWidth < 480) return;
$('.articles_container').eqHeights();
})

To execute it on window resized, do this:
$(window).resize(function() {
$('.articles_container').eqHeights();
}
Also, if you want to execute javascript upon media queries events, then use the sweet enquire.js javascript library.

Related

clearInterval function not clearing setInterval function

I utilized this resource to structure my code: http://www.w3schools.com/jsref/met_win_clearinterval.asp
var intervalID = setInterval(function(){ ogpeWrapper() }, 10);
function ogpeWrapper() {
$("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll('<div id="colWrapperContainer"></div>');
}(jQuery);
function myStopFunction() {
if (document.getElementById('colWrapperContainer')) {
clearInterval(intervalID);
setIntervalID = undefined;
}
}
My ogpeWrapper function is running, but the clearInterval function is not.
Basically, once $("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll(''); runs, I want the interval to stop running it.
Edit - 12:24pm CST:
This is the base code I utilize to wrap the listed elements -
(function($) {
$("#breadcrumbAds, #breadcrumbWrapper, #containerTopParsys, #leftColWrapper, #rightColWrapper").wrapAll('<div id="colWrapperContainer"></div>');
})(jQuery);
This code works, but it doesn't process the change until after the DOM has completely loaded. I need the function to work as soon as those elementals are all available. So I need to use a setInterval to process the function, then clear the interval once the function is processed.
If anyone knows of another way to do this, besides a setIterval, please let me know.
You need to create a definite if else condition within the variable so you know exactly when it will start and when it will stop. Also, because the minimum millisecond interval timing is not consistent across browsers, although you want it to detect really fast, I would recommend a "safer" number and use 100 as the minimum instead. The .length method is a handy little way for you to check if an element is on a page; You can use it as a pseudo dynamic true/false conditional. Lastly, in your .wrapAll() tag, I swapped your single and double quotes, as it is best practice to do such.
var colWrapper = setInterval(function(){
if ($('div#colWrapperContainer').length > 0) {
var doNothing = "";
clearInterval(colWrapper);
} else {
$("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll("<div id='colWrapperContainer'></div>");
}
}, 100);
Here is a working example for your reference Wrap Example
Update:
Example for putting the script inside the <body> tag (no window.load/document.ready) so that it runs independently as soon as it is loaded.
<script type="text/javascript">//<![CDATA[
//http://stackoverflow.com/questions/33483000/clearinterval-function-not-clearing-setinterval-function/33483267#33483267
//Auto Wrap Solution
//Alexander Dixon [11-02-2015]
var wrapThese = $("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper");
var colWrapper = setInterval(function () {
if ($('div#colWrapperContainer').length > 0) {
var doNothing = "";
clearInterval(colWrapper);
} else {
wrapThese.wrapAll('<div id="colWrapperContainer"></div>').addClass('success');
}
}, 100);
//]]>
</script>

How would you cycle through each image and check it for an error in a casperjs script?

How would you cycle through every image on a given page and check to see if it was loaded or errored out?
The following are not seeming to work in the phantomjs/casperjs setup yet cycling through and grabbing the src is working.
.load()
and
.error()
If the above does work, could someone show a proper usage that would work in a casperjs script?
The code I used looked similar to the following:
var call_to_page = this.evaluate(function() {
var fail_amount = 0;
var pass_amount = 0;
var pass_img_src = [];
var fail_img_src = [];
var img_src = [];
$("img").each(function(){
$(this).load(function(){
pass_amount++;
pass_img_src.push($(this).attr("src"));
}).error(function(){
fail_amount++;
fail_img_src.push($(this).attr("src"));
});
img_src.push($(this).attr("src"));
});
return [img_src, fail_amount, fail_img_src, pass_amount, pass_img_src];
});
Any help as to why the above code doesnt work for me would be great. The page is properly being arrived upon and I am able to mess with the dom, just not .load or .error. Im thinking its due to the images being done loaded, so Im still looking for alternatives.
CasperJS provides the resourceExists function which can be used to check if a particular ressource was loaded. The ressource is passed into a function, so custom constraints can be raised.
casper.then(function(){
var fail_amount = 0;
var pass_amount = 0;
var pass_img_src = [];
var fail_img_src = [];
var elements = this.getElementsInfo("img");
elements.forEach(function(img){
if (img && img.attributes && casper.resourceExists(function(resource){
return resource.url.match(img.attributes.src) &&
resource.status >= 200 &&
resource.status < 400;
})) {
pass_amount++;
pass_img_src.push(img.attributes.src);
} else {
fail_amount++;
fail_img_src.push(img.attributes.src);
}
});
this.echo(JSON.stringify([fail_amount, fail_img_src, pass_amount, pass_img_src], undefined, 4));
});
This can be done after the page is loaded. So there is no need to preemptively add some code into the page context.
In turn, the problem with you code may be that the callbacks never fire because the images are already loaded of already timed out. So there is no new information.
If you're not sure what kind of errors are counted, you can use a custom resources detection for all available types or errors.
var resources = []; // a resource contains at least 'url', 'status'
casper.on("resource.received", function(resource){
if (resource.stage == "end") {
if (resource.status < 200 || resource.status >= 400) {
resource.errorCode = resource.status;
resource.errorString = resource.statusText;
}
resources.push(resource);
}
});
casper.on("resource.timeout", function(request){
request.status = -1;
resources.push(request);
});
casper.on("resource.error", function(resourceError){
resourceError.status = -2;
resources.push(resourceError);
});
function resourceExists(url){
return resources.filter(function(res){
return res.url.indexOf(url) !== -1;
}).length > 0;
}
casper.start(url, function(){
var elements = this.getElementsInfo("img");
elements.forEach(function(img){
if (img && img.attributes && resourceExists(img.attributes.src) && !resourceExists(img.attributes.src).errorCode) {
// pass
} else {
// fail
}
});
});
I don't have much experience with caperjs, in my observation I identified below points
Note:
jQuery .load( handler ) and .error( handler ) both were deprecated from verson 1.8.
If you're using jQuery 1.8+ then attaching load and error events to img(tags) does nothing.
jQuery Ajax module also has a method named $.load() is shortcut form of $.get(). Which one is fired depends on the set of arguments passed.
Here are Caveats of the load event when used with images from jQuery Docs
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
So if you've version 1.8+ of jQuery the below block does nothing.
$(this).load(function(){
pass_amount++;
pass_img_src.push($(this).attr("src"));
}).error(function(){
fail_amount++;
fail_img_src.push($(this).attr("src"));
});
As a result this return [img_src, fail_amount, fail_img_src, pass_amount, pass_img_src]; statement will give us only img_src[with number of imgs as length] array filled with srcs of imgs in page. and other elements fail_amount, fail_img_src, pass_amount, pass_img_src will have same defaults all the time.
In the case of jQuery 1.8 below load and error events attachment with jQuery were meaningful(in your case these events were attached after they were loaded on page, so they won't show any effect with load and error callbacks), but the time where we attach events matters. We should attach these before the img tags or place the events in tag level(as attributes onload & onerror) and definitions of function handlers script should keep before any img tag or in very beginning of the body or in head
There're ways to figure out some are here:
use open-source plug-in like (Use imagesLoaded](https://github.com/desandro/imagesloaded)
Can use ajax call to find out whether the img.src.url were good or not?
Dimension based check like below function IsImageRendered
below I've but its old one not sure the browser support at this time. i recommend to go with above plug in if you can use it
var call_to_page = this.evaluate(function () {
function isImageRendered(img) {
// with 'naturalWidth' and 'naturalHeight' to get true size of the image.
// before we tried width>0 && height>0
if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
return false;
}
//good
return true;
}
var pass_img_src = [];
var fail_img_src = [];
var img_src = [];
$("img").each(function () {
var $img = $(this), $srcUrl = $img.attr("src");
img_src.push($srcUrl);
if (!$srcUrl)
fail_img_src.push($srcUrl);
else {
if (isImageRendered($img.get(0))) {
pass_img_src.push($srcUrl);
}
else {
fail_img_src.push($srcUrl);
}
}
});
var fail_count = fail_img_src.length,
pass_count = pass_img_src.length;
return [img_src, fail_count, fail_img_src, pass_count, pass_img_src];
});

Ubuntu HTML5 App: Change Tab on JS command

First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!

jquery slider animation playing fast after window is minimized

I'm using coda slider for a website and unfortunately after the window is minimized, the content slider plays super fast. I know it has something to do with Set time out, but I could not achieve perfect result yet. Any help on this will be appreciated. My script code is:
var theInt = null;
var $crosslink, $navthumb;
var curclicked = 0;
theInterval = function(cur){
clearInterval(theInt);
if( typeof cur != 'undefined' )
curclicked = cur;
$crosslink.removeClass("active-thumb");
$navthumb.eq(curclicked).parent().addClass("active-thumb");
$(".stripNav ul li a").eq(curclicked).trigger('click');
theInt = setInterval(function(){
$crosslink.removeClass("active-thumb");
$navthumb.eq(curclicked).parent().addClass("active-thumb");
$(".stripNav ul li a").eq(curclicked).trigger('click');
curclicked++;
if( 4 == curclicked )
curclicked = 0;
}, 8000);
setTimeout( nextCycle, 2000 );
};
$(function(){
$("#main-photo-slider").codaSlider();
$navthumb = $(".nav-thumb");
$crosslink = $(".cross-link");
$navthumb
.click(function() {
var $this = $(this);
theInterval($this.parent().attr('href').slice(1) - 1);
return false;
});
theInterval();
});
I always run into problems with setTimeout. My method is to do something like the following:
var timer = setTimeout( function(){nextCycle();}, 2000 );
Looks like the library is colliding with another library I'm using. I used another function which when the browser window is minimized or tab is changed on coming back to the page to refresh the page, in this case, all the scripts will reload and the slider will start from beginning. Though it is better if I could do it without refreshing the whole page and only by refreshing the scripts, or by playing the slider from the beginning somehow, but unfortunately my javascript knowledge is not much! here is the code:
$(window).blur(function() {
//Do Nothing//
});
$(window).focus(function() {
//This refreshes the whole page //
location.reload();
});

How can I rewrite this jQuery code into Javascript?

I'm using a WordPress theme that only has about 10 lines of jQuery, yet it's using the 90kb jQuery file. I want to change this jQuery code to Javascript, but I'm not very good at Javascript:
jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
$href = jQuery(this).attr('href');
$contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
$contentArea.fadeTo('fast', 1);
});
return false;
});
var $tabbed_area = jQuery('div#tabbed');
if ($tabbed_area.length) {
$tabbed_area.tabs({
fx: {
opacity: 'toggle'
}
});
};
Thanks in advance!
Personally I'd persist with jQuery. Although there is "only about 10 lines jQuery" what it is doing is quite substantial. By the time you have recreated a lot of what jQuery is providing you here you will have a fairly decent slab of javaScript to debug and maintain. That is the beauty of jQuery, to quote their tag line "write less, do more" Remember with jQuery you are eliminating a lot of annoying cross browser quirks.
Edit: See tbranyen's answer for a practical example of why jQuery is worth it
Use a CDN version of jQuery, like Google's and you will be using jQuery that your uses may already have cached and therefore does not have to be downloaded again. jQuery UI can also be served in the same way. See this article: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
EDIT
Reading your question further "I'm not very good at javaScript" is all the more reason to stick with jQuery. Let it do all the heaving lifting for you. HOWEVER don't use jQuery as an excuse not to learn more about javaScript, the more you learn about javaScript the more you will be able to get out of jQuery.
My solution is fragmented, its not complete, and I do not expect points for this answer. This was me taking a stab at replicating jQuery's code in vanilla JS, purely as scientific justice to your question. I consider myself good at JavaScript, but even I know my limitations and time constraints. I only have one life on this planet and its honestly not worth my time to write out a tabs plugin and animation for your Wordpress site.
Just take a look at the code difference. If you're really scared about people downloading, you should ask yourself what makes your site so much different than the thousands/millions? of other sites that are visited by millions of people?
Writing this stuff is tedious, that's why if I have to do these things, I use jQuery. However, lets say you don't care about older browser support. You didn't mention that, I have a solution at the very bottom that does more, but WILL not work with older browsers or work period for that matter.
The original
Very little code to do immensely complicated stuff.
jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
$href = jQuery(this).attr('href');
$contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
$contentArea.fadeTo('fast', 1);
});
return false;
});
Attempting to write from scratch
// Not even close to finished solution
(function(window, document) {
var tabbed = document.getElementById('tabbed');
// Semi-normalized event handling, not even a fraction as good as jQuery's
function attachEvent(node, type, callback) {
if(node.attachEvent) {
return node.attachEvent('on'+type, function() {
callback.apply(window.event.target, arguments);
});
}
return node.addEventListener(type, function(e) {
callback.apply(e.target, arguments);
}, true);
}
// Semi-delegation again, not even a fraction of what jQuery offers
attachEvent(document, 'click', function(e) {
var href = this.href;
var body = document.body;
var elements = [];
var slice = [].slice;
var concat = elements.concat;
// This is just the start of what it would take to emulate what jQuery is doing to match all those items
// Without a reliable selector engine like querySelectorAll (not even that reliable) you'd need to match.
elements = concat(slice.call(body.getElementById('main-tabbed-area').getElementsByTagName('a')));
elements = concat(slice.call(body.getElementsByTagName('...');
// Not even going to attempt fading
// jQuery again does all this
});
if(tabbed && tabbed.tagName === 'div') {
// No idea what tabs is? A plugin? Good luck!
}
})(this, this.document);
Code is slightly more modern... but still jeesh look at all that code
function xhr(url, callback) {
var request = new window.XMLHttpRequest();
request.open('GET', url, true);
request.onreadystatechange = function(e) {
if(e.readyState === 4) {
callback(e.responseXML);
}
};
request.send(null);
}
// No idea what contentArea is
var contentArea = ...???;
(function(window, document) {
var tabbed = document.getElementsById('tabbed');
document.addEventListener('click', function(e) {
var href;
var elements = document.querySelectorAll('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a');
var match = false;
elements.forEach(function(element) {
if(this === element) {
match = true;
}
});
if(match) {
href = e.target.href;
// Some CSS3 class that does a fade out
contentArea.classList.add('fadeOut');
xhr(href, function(data) {
var data = data.getElementById('main-area').innerHTML;
contentArea.innerHTML = data;
contentArea.classList.remove('fadeOut');
// Some CSS3 class that does a fade in
contentArea.classList.add('fadeIn');
});
return false;
}
}, true);
if(tabbed && tabbed.tagName === 'div') {
// Still no idea what tabs is? A plugin? Good luck!
}
})(this, this.document);

Categories