Resizing div is slow in Chrome - javascript

I have a 1440*900 monitor; a page with header, footer, and two DIVs between them (the first is my main-content DIV and the second is under it, with the same width)
I need to resize the second DIV (it uses the same background as the main-content DIV does) to feel the gap between footer and bottom of window (if there is some)
I use this code :
while($("#page").height() < wh){
$("#spacer").css('height', (parseInt($("#spacer").css('height').replace('px', '')) + 1) + 'px');
}
I use it in document-ready (jquery), but it freezes in Chrome (but not in firefox).

You could try making classes in your CSS file for your different sizes, and then just using jQuery to change the class. Might be faster.
.addClass
or
.attr('heightClass', 'whateverClassYouWant')

What's that? That code is repeated. And I wouldn't use while. I would use an event detector,
$(window).resize(function(e) {
if ($(window).height>value) {
//do stuff
}
else if ($(window).height<value) {
//do stuff
}
}
);
$(document).ready ( function(e) { //the same } );
While makes it slower. try not to use while in that ocasions, while hasn't been created for that, there are event listeners, while stays there till the condition changes or you break it.

Related

Local Storage, and how to delay div visibility

I am using localstorage to show a div only once, and although the code it works very well, I would like to know how I can delay the visibility of this div ( #alert ) for 1 - 2 seconds (the first time the visitor is shown), and then do a fade in, so that it does not appear suddenly.
My code:
const showMsg = localStorage.getItem('showMsg');
if(showMsg === 'false'){
$('#alert').hide();
}
$('.closebtn').on('click', function(){
$('#alert').fadeOut('slow');
localStorage.setItem('showMsg', 'false');
});
You can run the demo here:
https://jsfiddle.net/0966x2dw/7/
My problem has a solution?
Thanks.
EDIT:
Ops, right. I used CSS Transitions on my #alert div, and now it's much better.
Thanks.
https://jsfiddle.net/0966x2dw/23/
First add "display: none;" to your .alert. Then you can do something like:
if(showMsg === 'false'){
$('.alert').hide();
} else {
$('.alert').delay(1000).fadeIn();
}
This will cause your alert div to bump the content below it down. You may want to use slideDown() instead to make it less abrupt.
(Note that if your alert is critical to your users, you should adjust this to make sure it displays for the small % of people who have Javascript off.)

jQuery syntax added var

I needed a jQuery function to fix my div when the page is scrolled.
I found this:
var fixed = false;
var topTrigger = $('#sticker').offset().top;
$(document).scroll(function() {
if( $(this).scrollTop() >= topTrigger ) {
if( !fixed ) {
fixed = true;
$('#sticker').css({'position':'fixed', 'top':'0'});
}
} else {
if( fixed ) {
fixed = false;
$('#sticker').css({'position':'relative'});
}
}
});
Now, since I'm not a super beginner with jQuery, I tried to skim it and understand it. The only things I don't understand are the things related to the var:fixed. I tried to delete the var and the if statement related to that and the function works perfectly.
My question : why is that variable there, what does it mean, what feature does it add to the entire function?
Why should I keep it there instead of deleting everything related to that variable?
The scroll event will be fired multiple times as the user scrolls. If you keep on changing the DOM attributes, then the performance of the site may slow down.
To avoid applying the style multiple times, they are having a flag called fixed. So once the user has scrolled a particular height, they will trigger change the DOM to be fixed. Later they need not again change the CSS style.
Only if the user scrolls back less than the threshold they need to change the style again.

Creating Class on Image with JQuery

Right now I am trying to add a class to images when they are landscape using the following code:
$('.gallery img').each(function() {
if ($(this).width() > $(this).height()) {
$(this).addClass('landscape');
}
});
The code is working some times, but sometimes the class is not added, thus the styles I have are not applied. I have tried with and without the $(document).ready function, along with putting it next to the images rather than at the end of the code, but nothing is consistently adding the class to the landscape images. I'm not sure what else to try. Any suggestions?
Also listen to a load event, since some images might not be loaded (and therefore have unknown width/height):
// Put this in your $(document).ready
function handleImage($image) {
if ($image.width() > $image.height()) {
$image.addClass('landscape');
}
}
$('.gallery img').each(function() {
handleImage($(this));
}).load(function() {
handleImage($(this));
});
Note that having width and height attributes on image tags is recommended if you know the dimensions beforehand. Adding those attributes would void the need to have an onload handler.

How to hide all text, which are smaller than certain pixel and bring them back later using Javascript?

I'm working on a project, which in some cases requires to hide all small text (eg. less than 12px), and on some other event, bring them back. It's not a website, but something happening on the webkit browser. I don't have control over the content on the page (developed by the third party developers), but have control to modify it. I know I can loop through all tag elements and check font sizes and hide them if smaller than 12px, but it's not only inefficient, but the text can be changed to be shown again, say after an ajax call, which is "prohibited". Other solution would be to run that loop every couple seconds, but it's an expensive process.
Other task is to show small text on some other event, which is not too difficult to implement by just using simple custom class.
You can run the code on page-load, and then when any AJAX call completes using jQuery's Global AJAX Event Handlers: http://api.jquery.com/category/ajax/global-ajax-event-handlers/
$(function () {
function findSmallText($root, state) {
if (typeof $root == 'undefined') {
$root = $(document);
}
if (typeof state == 'undefined') {
state = 'none';
}
$.each($root.find('p, div, span, font, button, a'), function () {
if ($(this).css('font-size').replace(/(px|pt|em)/gi, '') <= 12) {
$(this).css('display', state);
}
});
}
//run the function when the DOM is ready
findSmallText();
//also run the function when any AJAX request returns successfully
$(document).ajaxSuccess(findSmallText);
});
You can pass the findSmallText function two arguments:
$root: (jQuery object) the root element to start looking for small text, limit this as much as possible to increase performance (so unnecessary elements don't have to be scanned).
state: (string) the display property to add to the elements with small text, you can use block to show the elements.
if the HTML structure doesnt change (no extra containers added thru AJAX) simply analyze the page onLoad (kinda like what Jasper suggests) but instead of re-running the analysis after each AJAX call you add a new class - let's call it .HideMeInCertainCases for the fun of it. That way you can hide / show everything you want with a simple selector whenever you want.
So instead of this line: $(this).css('display', state); use $(this).addClass('HideMeInCertainCases');
When the event you were talking about occurs you can then toggle the display state with this selector $("HideMeInCertainCases").toggleClass("hideMe"). Changing the display-attribute directly might break your layout as the nodes containing text might have different displays to begin with (block, inline, inline-block...). Of course .hideMe { display:none; } should be somewhere in your stylesheet. If you want the layout to stay the same and only hide the content use visibility instead of display

How to disable user's input while loading page with jQuery?

I have a heavy-jquerized page with some links, various user inputs and such.
I use jquery, with actions defined in a
$(document).ready( function() {
....
} );
block.
But while the page is loading (or, even worse - reloading), and a user clicks a link, the href action from it is triggered, as the javascript isn't loaded / active yet.
I wanted to block it somehow. One way that came to my mind is to put a transparent div over whole document, that would receive the click events instead of the layer below it. Then, in my .ready function in javascript, I could hide that div making it possible to use the page.
Is it a good practice? Or should I try some different approach?
Another option is to use the jQuery BlockUI plugin (which probably usew the same or similar idea behind the scenes).
If you don't want your links to act like links (ie their href is never meant to followed), why make them links in the first place? You'd be better served by making your clickable elements a div or span (something without a default action), and attaching the click handler as per normal.
I'd really advise against blocking the ui with a div - it seems the entirely wrong approach, making the page non-functional to someone with JS disabled, as well as blocking other common tasks like copying text.
In light of the clarification, to block the UI only if JS is enabled, but not yet loaded, I'd suggest the following.
HTML (first thing after body):
<script type="text/javascript">document.write('<div id="UIBlocker">Please wait while we load...</div>')</script>
CSS:
#UIBlocker
{
position: fixed; /* or absolute, for IE6 */
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Or, if you prefer not to use document.write, leave the UIBlocker div as straight HTML at the top of body, but have the following in head
HTML:
<noscript>
<style type="text/css">
#UIBlocker { display: none !important; }
</style>
</noscript>
This will ensure it does not block for non-JS enabled browsers
A transparent div could work, assuming it’s positioned above everything. (I’m never quite clear how visible an element has to be to receive click events.)
You might want to make the div visible though; it could be equally confusing for visitors if they can see everything on the page, but not click it.
You’ll probably need to use JavaScript to make the div as tall as the page though.
The overlay DIV should work. Another option would be to place all the content inside a hidden container visibility: hidden then toggle to visible as the last $(document).ready statement.
As you said it yourself javascript isn't loaded yet. Maybe the css isn't loaded either.
so something with visual element will not work i think. IF you want to do some with the viaual elements (css) you have to hardcode it in the html node <tagname style="blabla">
You could possibly add the href behavious in a later stadium when the js is loaded.
What you get is a <span> with a title and this should set the behaviour or something. I used a title, but can be a different attribute.
This doesn't use any jquery, only for loading
$(document).reade(function () {
relNoFollow();
});
function relNoFollow() {
var FakeLinks = document.getElementsByTagName('span');
if( FakeLinks.length > 0 ) {
for( var i = 0; i < FakeLinks.length; i++ ) {
if( FakeLinks[i].title.indexOf( 'http://' ) != -1 ) {
FakeLinks[i].onmouseout = fakelinkMouseOut;
FakeLinks[i].onmouseover = fakelinkMouseOver;
FakeLinks[i].onclick = fakelinkClick;
}
}
}
}
function fakelinkMouseOver() {
this.className = 'fakelink-hover';
}
function fakelinkMouseOut() {
this.className = 'fakelink';
}
function fakelinkClick() {
window.location.href = this.title;
}

Categories

Resources