Hi — I've inherited a website that has a little javascript script that isn't working properly. I didn't code it myself and am a javascript n00b, so please forgive my ignorance.
The site switches from 3-column view to 1-column view depending on window size, and there's a script to make one particular section of the site convert neatly between the two views (by setting the column heights such that they stack neatly). I've noticed that if I resize the window without refreshing, the column heights fail to adjust. How can I fix this?
Thanks!
<script type="text/javascript">
function adjust_col_heights() {
if (window.innerWidth > 991) {
var col_1_height = document.getElementById('col-1').clientHeight;
var col_2_height = document.getElementById('col-2').clientHeight;
var col_3_height = document.getElementById('col-3').clientHeight;
console.log("adjusting heights from:", col_1_height, col_2_height, col_3_height);
var col_max_height = Math.max(Math.max(col_1_height, col_2_height), col_3_height);
var css_height = col_max_height + "px";
document.getElementById('col-1').style.height = css_height;
document.getElementById('col-2').style.height = css_height;
document.getElementById('col-3').style.height = css_height;
document.getElementById('poem').style.position = "absolute";
}
else {
document.getElementById('poem').style.position = "relative";
}
}
adjust_col_heights();
window.onresize = adjust_col_heights;
</script>
window.onload = function () {
resizeElements();
window.addEventListener('resize', resizeElements);
}
function resizeElements() { ... }
Related
I am trying to make a full RWD webpage using HTML5, CSS3, and JavaScript.
I have used #media in my CSS stylesheet file to set aside width:0; and hidden overflow, in small devices. I added a button that calls java scripts to minimize article and maximize aside menu, and another button to minimize aside and return article.
The following code is called:
function openaside() {
document.getElementById("article").style.width = "0";
document.getElementById("aside").style.width = "100%";
document.getElementById("showasidebtn").style.width = "0";
document.getElementById("hideasidebtn").style.width = "25pX";
}
function closeaside() {
document.getElementById("article").style.width = "100%";
document.getElementById("aside").style.width = "0";
document.getElementById("showasidebtn").style.width = "25px";
document.getElementById("hideasidebtn").style.width = "0";
}
My page correctly responds to screen size and my scripts work fine. However when I use these scripts to change style and then change screen size, my article and aside width do not dynamically change until I refresh the page.
I have added the following JavaScript code to refresh page when screen is resized:
window.addEventListener("resize", onresize);
function onresize(){
location.reload(false)
}
Thanks every one I Find a way, instead of
function onresize(){
location.reload(false)
}
I use:
function onresize(){
document.getElementById("article").style.width = "";
document.getElementById("aside").style.width = "";
document.getElementById("showasidebtn").style.width = "";
document.getElementById("hideasidebtn").style.width = "";
}
But article minimize when the screen is moved in phones (e.g. scrolling). So now phone users should first scroll then open side menu. Could you help me find a better way? Is there any way to call a script when screen width exceed a certain amount?
I seems in java script we don't have independent event listener for screen size. But I realized we can get screen size, so I use following code:
function onresize() {
window.addEventListener("resize", onresize);
var viewportwidth;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerWidth
}
//then I checked size to reset if nesecery
if (viewportwidth > 600) {
document.getElementById("article").style.width = "";
document.getElementById("aside").style.width = "";
document.getElementById("showasidebtn").style.width = "";
document.getElementById("hideasidebtn").style.width = "";
}
JAVA SCRIPT IS AMAZING.
Thanks all.
I know that you don't normally like doing things like this but I'm at University and have to do a project with several different stylesheets for the same page. I have been given JavaScript code to enable me to resize the page when the window is resized.
This code works however I am getting a peculiar effect on one of the stylesheets where the content div takes up most of the page when it shouldn't, this page has measurements in ems whereas my other stylesheets use px but I am supposed to use ems for at least one page. Although I could give my lecturer a reason for it being bigger I would prefer to fix the problem. The JavaScript code I am using is shown below:
function smoothresize() {
blockwidth = 59.4; /*This is in ems as per the lecturers request a well and is the size of the container div I created*/
minmargin = 0;
minsize = 10;
emwidth = (minmargin * 2) + blockwidth;
computeResize(emwidth, minsize, false)
}
function computeResize(wide, minsize, jerk) {
windowpixels = document.documentElement.clientWidth;
pixelsize = windowpixels / wide;
emsize = calculateEmsize(pixelsize, minsize, jerk);
b = document.getElementsByTagName('html')[0];
b.style.fontSize = emsize + "em";
}
function calculateEmsize(psize, minsize, jerk) {
if (psize > minsize) {
raw = psize;
}
else {
raw = minsize;
}
if (jerk) {
result = ((Math.floor(raw)) / 16);
}
else {
result = raw / 16;
}
return result
}
This is where I have Implemented the code in my XHTML:
<body onload="smoothresize()" onresize="smoothresize()">
I wouldn't be able to use jQuery as a solution to the problem either, I would only be able to modify the code given.
Any help in this matter Would be greatly appreciated
Check out jQuery's user interface plugin. It contains a "resizable" option; you ought to be able to add <script type="text/javascript">window.onload=function(){};</script> that loads the desired JQUI function upon page load.
I am making a responsive site in which I add event listeners to blocks to slide down. If I resize my browser window to become wider I want to execute a slideUp to this blocks so that they're all neatly slided up. Does anyone know how to achieve this?
My jquery function:
function mobileFunctions(){
if($(window).width() < 600){
$(".replace-url").attr('href', '#');
$(".list-categories li").removeClass('click');
categoryActive();
}
}
function categoryActive(){
$(".title-click").click(function(){
var e = $(this).parent("li");
var i = ".list-categories li";
var c = "active";
var d = ".content-category";
if(!$(e).hasClass(c)){
$(i).removeClass(c);
$(i).children(d).slideUp("slow");
}
$(e).children(d).slideDown("slow");
$(e).addClass(c);
});
I believe you are looking for this?
$('window').resize(function() {
var someValue = 1024;
if ($('window').width() > someValue) {
// function here...
}
});
I have a strange issue that might have to do with jQuery document ready. Below is an html and script block that contains the usual social networking scripts. The Javascript block below displays the dd_outer div on the left edge of the body div, and when the browser window is shrunk, the div is faded out and the dd_footer div is faded in. The fadein and fadeout between the two divs works OK.
The problem is two fold: one issue is when the browser window is full width (1200px+), the Facebook script will not load and display consistently; it sometimes appears and sometimes doesn't, sometimes after a page reload and sometimes doesn't. (No browser or .htaccess caching is involved). Only the Facebook share fails to show consistently; all other services show OK.
The second problem that when the browser window is narrow - 650 px or so, when the dd_outer div is not displayed and the dd_footer div is - the footer div will not show on a page reload until the browser window is moved the smallest amount. Then the the div will display, Facebook share and all. For a mobile device, this is a problem because the browser window will be narrow to begin with and shouldn't need to be "nudged" to make the dd_footer div display.
This problem may have come into play because I have adapted this code from a WordPress plugin that used options to set the position of the dd_outer div and scroll height. That's the reason for the variables above the document ready call.
Is this the issue with what seems to be a document ready issue?
How can the variables be integrated into the script itself? It doesn't matter if they are hardcoded; I can change them when needed.
I'd throw this in a jsfiddle to demo but the divs won't realistically float with the window resizing.
I haven't included the CSS for clarity.
This is the html and social script block:
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'>
<div class="sbutton"><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like layout="box_count" show_faces="false" font=""></fb:like></div>
<div class="sbutton">
Tweet<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>
<div class="sbutton"><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script><g:plusone size="tall"></g:plusone></div>
<div class="sbutton"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/Share" data-counter="top"></script></div>
</div></div></div>
In the footer is <div id="dd_footer">that contains the same social scripts as above</div> and are faded in and out by the script below:
This is the jQuery that positions the dd_outer social services to the left and fades it out and fades in the dd_footer div.
<script type="text/javascript">
var dd_top = 0;
var dd_left = 0;
var dd_offset_from_content = 70; var dd_top_offset_from_content = 10;
jQuery(document).ready(function(){
var $floating_bar = jQuery('#dd_ajax_float');
var $dd_start = jQuery('#dd_start');
var $dd_end = jQuery('#dd_end');
var $dd_outer = jQuery('.dd_outer');
// first, move the floating bar out of the content to avoid position: relative issues
$dd_outer.appendTo('body');
dd_top = parseInt($dd_start.offset().top) + dd_top_offset_from_content;
if($dd_end.length){
dd_end = parseInt($dd_end.offset().top);
}
dd_left = -(dd_offset_from_content + 55);
dd_adjust_inner_width();
dd_position_floating_bar(dd_top, dd_left);
$floating_bar.fadeIn('slow');
if($floating_bar.length > 0){
var pullX = $floating_bar.css('margin-left');
jQuery(window).scroll(function () {
var scroll_from_top = jQuery(window).scrollTop() + 30;
var is_fixed = $dd_outer.css('position') == 'fixed';
if($dd_end.length){
var dd_ajax_float_bottom = dd_end - ($floating_bar.height() + 30);
}
if($floating_bar.length > 0)
{
if(scroll_from_top > dd_ajax_float_bottom && $dd_end.length){
dd_position_floating_bar(dd_ajax_float_bottom, dd_left);
$dd_outer.css('position', 'absolute');
}
else if ( scroll_from_top > dd_top && !is_fixed )
{
dd_position_floating_bar(30, dd_left);
$dd_outer.css('position', 'fixed');
}
else if ( scroll_from_top < dd_top && is_fixed )
{
dd_position_floating_bar(dd_top, dd_left);
$dd_outer.css('position', 'absolute');
}
}
});
}
});
jQuery(window).resize(function() {
dd_adjust_inner_width();
});
var dd_is_hidden = false;
var dd_resize_timer;
function dd_adjust_inner_width() {
var $dd_inner = jQuery('.dd_inner');
var $dd_floating_bar = jQuery('#dd_ajax_float')
var width = parseInt(jQuery(window).width() - (jQuery('#dd_start').offset().left * 2));
$dd_inner.width(width);
var dd_should_be_hidden = (((jQuery(window).width() - width)/2) < -dd_left);
var dd_is_hidden = $dd_floating_bar.is(':hidden');
if(dd_should_be_hidden && !dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeOut(); }, -dd_left);
jQuery('#dd_footer').fadeIn();
}
else if(!dd_should_be_hidden && dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeIn(); }, -dd_left);
jQuery('#dd_footer').fadeOut();
}
}
function dd_position_floating_bar(top, left, position) {
var $floating_bar = jQuery('#dd_ajax_float');
if(top == undefined) top = 0 + dd_top_offset_from_content;;
if(left == undefined) left = 0;
if(position == undefined) position = 'absolute';
$floating_bar.css({
position: position,
top: top + 'px',
left: left + 'px'
});
}
</script>
jQuery .ready() does not wait for iframes and other external media to load. These social buttons tend to work by inserting an iframe. The load event does wait for iframes etc, so you could try using that event instead, i.e.
jQuery(window).load(function () {
/* put the code you had inside .ready() here */
});
The problem comes with your idea: $(document).ready() fires when the DOM is ready, not when all scripts are ready!
an idea would be to search for trigger of that social-APIs you are using or just delay your calculations (e.g. via setTimeout).
Keep in mind that they are asyncron, even if you specify "async" on the script-tag to be false, you still dont know when they will activate or are finished.
I suggest to use the standard DOM event window.onload if you want to make sure that all the external assets, scripts, images, etc. are loaded first before you do something:
window.onload = function () {
// your script that needs to run after all the external assets are loaded
}
Reference: https://developer.mozilla.org/en-US/docs/DOM/window.onload
I just ran into similar problems with the facebook script... I just used the integration in the HEAD-section with javascript and added an "asynchronous"-attribute to the javascript-embedding script which then fires an asynchronous "heeey, facebook is ready now, too"-event to my jQuery-eventqueue...
I can't help you in detail, because I don't totally understand what you WANT to do and would reorganize the whole code A LOT... so - contact me private (email/skype) or try figuring out... I used that lines of code: pastie.org/private/9m4b9eet1dzzkl6duqpkrg
I saw a cool style/js function (I can tell what it is) that implemented on a side menu.
You know the situation when you have a long center page and one of / both of you sides ends and that leave a blank space? Well this site implemented this thing that just when the user scrool to the place where the side menu end - the menu get absolute postion and doesnt move.
How can I do this?
If you want to see an example you can look here (just scroll and look on the sides)
I believe you can achieve similar effect using this: http://www.wduffy.co.uk/blog/keep-element-in-view-while-scrolling-using-jquery/comment-page-1/ (just making it move with 0 as speed parameter instead of slow, as in the example) and adding conditions about whether the current position fits within the box it is displayed (you can take height of the box - menu being moved on page or box that contains the menu - by using .height() jQuery function).
EDIT:
The page you referenced uses the following JavaScript code to support what you try to accomplish:
<script type="text/javascript">
$(function(){
var seoHeight = $$('dvIndexSeoMaster').height();
seoHeight = (seoHeight > 0) ? seoHeight : 0;
var documentHeight = $(document.body).height() - 120 - seoHeight;
var fixedMode = false;
var hasFixedClass = false;
var leftColElm = $sc('dvFixed');
var leftColPos = leftColElm.offset().top;
var leftColHeight = leftColElm.height();
var rightColElm = $$('dvIndexMasterRightCol');
var rightColPos = rightColElm.offset().top;
var rightColHeight = rightColElm.height();
function scrollElm(elmPos,elmHeight,objElm, cssClass){
var fixedMode = false;
var hasFixedClass = false;
var windowTop = $(window).scrollTop();
(windowTop >= elmPos && (windowTop + elmHeight) < documentHeight) ? fixedMode = true : fixedMode = false;
if( fixedMode){
$(objElm).addClass(cssClass);
hasFixedClass = true;
}else if( (fixedMode == false)){
$(objElm).removeClass(cssClass);
hasFixedClass = false;
}
};
$(window).scroll(function(){
scrollElm(leftColPos,leftColHeight,leftColElm,'make-fixed');
scrollElm(rightColPos,rightColHeight,rightColElm, 'make-fixed');
});
});
</script>
And the make-fixed CSS class has the following definition:
.make-fixed {
position: fixed;
top: 0;
z-index: 200;
}
You can make an element stay in the same place, even as the user scrolls, with the CSS position:fixed property: http://www.w3.org/TR/CSS2/visuren.html#fixed-positioning