JS set style for size function - javascript

My JS function "set style for size" will not call the bodysmall CSS style sheet no mater how small I make the screen width (screen.width <=480).
However the function will call the bodysmall CSS style sheet if I reverse the function.
(screen.width >=480)
Which proves to me the JS function is working. I suspect there is something wrong with my event handler.
I am not familiar with JavaScript yet so any help would be greatly appreciated.
this is my code below.
<script type="text/javascript">
function setStyleForSize() {
if (screen.width <= 481) {
document.body.className = "bodySmall";
}
else {
document.body.className = "bodyNormal";
}
}
function addEventHandler(oNode, evt, oFunc) {
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc, true);
}
addEventHandler(window, "load", function() { setStyleForSize(); } );
addEventHandler(window, "resize", function() { setStyleForSize(); } );
</script>

Try this one instead of yours:
function addEventHandler(oNode, evt, oFunc) {
if ( document.addEventListener ) {
oNode.addEventListener(evt, oFunc, false);
return oFunc;
} else if ( document.attachEvent ) {
var bound = function() {
return fn.apply(oNode, arguments);
};
oNode.attachEvent("on" + evt, bound);
return bound;
}
}
NOTE: You can't specify which event handler has to be used with typeof(window.event), so your if statement is incorrect
See the DEMO

screen.width is never changes, use window.innerWidth instead:
function setStyleForSize() {
if (window.innerWidth <= 481) {
document.body.className = "bodySmall";
}
else {
document.body.className = "bodyNormal";
}
}

Related

Getting the width in jQuery isn't working

I'm not sure what I am doing wrong here but the following code for some reason is throwing up undefined variables.
What variable should I be using to get and test the width of the window?
jQuery(document).ready(function() {
function dostuff(){
if (window.width < 1050) {
console.log("not working?")
} else {
console.log(window.width)
}
}
jQuery(window).resize(function(){
dostuff();
});
});
The window doesn't have a width property. You need to use:
window.innerWidth
Also, the code can be reduced by:
jQuery(function($) {
function dostuff() {
if ($(window).width() < 1050) {
console.log("not working?")
} else {
console.log($(window).width())
}
}
$(window).resize(dostuff);
});

custom when statement not firing functions

I am trying to make a when statement but it is not working as planned. Basically its a function to call another function when try. First before I explain further here is the syntax
when(function() {
//code here
});
Now basically... Think this way.. We have a progressbar.. We also have a custom event such as...
var pBarEvent = document.createEvent('Event');
pBarEvent.initEvent('pbardone', true, true);
document.addEventListener('pbardone', function() {
//code here
});
//if progress bar reaches 100 dispatchEvent
if (document.querySelector(".progress-bar").style.width === 100 + "%")
{
document.dispatchEvent(pBarEvent);
}
Now that piece of code is an example. If the document loads and its for instance at 50% it wont trigger until you add another event such as keydown or click. I dont want to do that I want to do.... "when" progress bar width equals 100% trigger it. Thats basically what needs to happen. So here is the code for the when statement so far (keep in mind its not the best looking one. As I dont normally do this but I wanted to keep this dynamic and who knows someone who later wants to do this can look at this question)
when function
function when(func)
{
var nowActive = false;
if (!typeof func === 'undefined')
{
func = new Function();
}
if (func)
{
nowActive = true;
clearInterval(whenStatementTimer);
}
else
{
nowActive = false;
var whenStatementTimer = setInterval(function() {
switch(func)
{
case true:
{
nowActive = true;
when();
break;
}
case false:
{
nowActive = false;
when();
break;
}
}
}, 1000);
}
if (nowActive === true)
{
func();
}
}
Now this does not work when I go to try something like....
when(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("100%");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style("body", "background", "black");
});
});
It does not trigger. I need help possibly getting this when statement to work. What am I doing wrong? What can I do to fix it? No errors get thrown but it never fires.
edit based on answer
Function tried
function when(currentValue)
{
try
{
var o = {};
o.currentValue = currentValue;
o.do = function(func)
{
if (!typeof func === 'undefined')
{
func = new Function();
}
if (this.currentValue)
{
func();
}
else
{
setTimeout(this.do(func), 100);
}
};
return o;
}
catch(e)
{
console.log(e);
}
}
used as
when(true).do(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
});
This does not work. It never fires. But if I use a onclick listener as such it fires
document.addEventListener("click", function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
}, false);
function when(statement){
o={};
o.statement=statement;
o.do=function(func){
awhen(this.statement,func);
};
return o;
}
function awhen(statement,func){
if(eval(statement)){
func();
}else{
window.setTimeout(function(){awhen(statement,func);},100);
}
}
Use:
when("true").do(function(){});
It works now :) . Its important to put the condition in ""!

Javascript is not "opening" url's

I am not sure what's wrong with this script. It "should" work.
HTML
<img src="https://placehold.it/350x150" alt="" onclick="goTo('img1');">
Javascript
function goTo(img) {
if( img === 'img1' ) { window.open('https://www.google.com/','_blank'); }
else if( img === 'img2' ) { window.open('https://www.yahoo.com/','_blank'); }
etc...
else{ alert("This image is not recognized: " + img ); }
}
JsFiddle: https://jsfiddle.net/omarjuvera/xuzc70gn/2/
Edit: On the website, I have the javascript code inside a .ready(), like so:
$( document ).ready(function() {
function goTo(img) {
if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
else{ alert("This image is not recognized: " + img ); }
}
...more functions...
});
Just put the goTo function outside of .ready() event like following:
function goTo(img) {
if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
else{ alert("This image is not recognized: " + img ); }
}
$( document ).ready(function() {
...more functions...
});
Your goto function is not declared in global scope, and thus cannot be found.
Try:
window.goTo = function (img) {
// your code
}
By default, JsFiddle runs your code on page load. In other words, it wraps your goTo() function in anther function, like this:
window.onload=function(){
function goTo(img) {
if( img === 'img1' ) {
window.open('https://www.google.com/','_blank');
}
else if( img === 'img2' ) {
window.open('https://www.yahoo.com/','_blank');
}
else {
alert("This image is not recognized: " + img );
}
}
}
This makes it inaccessible from, for example, an onclick attribute in HTML.
To fix this, you need to change the Load type setting to "No wrap - in <body>":
See updated fiddle

Fire multiple functions on resize events

I am trying to fire multiple functions when the window resizes. But only one function works at the time. Please correct this code.
function resize() {
var $containerWidth = $(window).width();
if ($containerWidth > 1140) {
//code...
}
else {
//code...
}
}
resize();
function resizepos() {
var topPosition = $('.redcus').offset().top;
$('.blackcus').css('top',(topPosition+40)+'px');
}
resizepos();
$(window).resize(function(){
resize();
resizepos();
});
Why don't you try the code like this :
function resize() {
var $containerWidth = $(window).width();
if ($containerWidth > 1140) {
//code...
}
else {
//code...
}
resizepos();
}
And try to change your function name when you calling it in jquery, ex "Allresize" and in the contents of Allresize function there is "resizepos" function. Don't use "resize" double, please check it again.
Sorry for the bad format, i can't handle it from my android.
I don't really use jQuery but edit this if I'm wrong:
$(window).on('resize', resize);
$(window).on('resize', resizepos);

Multiple javascript window.onload solution

Before i ask this question, i never post about questions like this but I don't understand how to implement it in my code. i have code like this
window.onload = function() {
var url = getQueryVariable("url");
document.getElementById('view').src = url;
}
window.onload = function() {
var linkDirect = document.getElementsByClassName("frame");
for (var i = 0; i < linkDirect.length; i++) {
linkDirect[i].href = "http://namablog.blogspot.com/p/demo.html?url=" + linkDirect[i].href
}
}
then, how can I make the code execution using only one window.onload
You can use addEventListener or any jQuery equivalent.
window.addEventListener('load', function (){
alert('Function #1');
});
window.addEventListener('load', function (){
alert('Function #2');
});
Be sure to call these before the window is loaded.
window.addEventListener will not work in IE so use window.attachEvent
You can do something like this
function fun1(){
// do something
}
function fun2(){
// do something
}
var addFunctionOnWindowLoad = function(callback){
if(window.addEventListener){
window.addEventListener('load',callback,false);
}else{
window.attachEvent('onload',callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
Just my 2 cents, My personal fav way of doing this is as follows:
function window_onload(cb) {
try {
if (typeof cb == 'function') {
if (document.readyState == 'complete') cb();
else if (window.hasOwnProperty('jQuery')) jQuery(window).on('load', cb);
else if (window['addEventListener']) document.addEventListener('load', cb, false);
else if (window['attachEvent']) {
// iFrame
if (window['frameElement']) document.attachEvent('onreadystatechange', function(){ if (document.readyState === 'complete') window_onload(cb); });
else window.attachEvent('onload', cb);
}
else {
var fn = window.onload; // very old browser, copy old onload
window.onload = function() { fn && fn(); ready(); };
}
}
}
catch (err) { if (window['console'] && console['error']) console.error("ERROR[window_onload()]", err); }
return window;
}
This pretty much covers just about everything. What little (mainly extremely old browsers I suppose?) it doesn't cover, you could easily debug, if needed. This also goes ahead and launches the callback if the document is already 'loaded'.
The simplest solution that has worked for me:
function doOnLoad() {
onloadfn1();
onloadfn2();
onloadfn3();
}
window.onload = doOnLoad;
This article has explained it in details: http://developer.expressionz.in/blogs/2009/03/07/calling-multiple-windows-onload-functions-in-javascript/
I hope this helps some of you.

Categories