HTML: How to make scrolling work faster here - javascript

I have developed an application about product and their detials. In that application, at a page, it loads almost 10,000 product details on single page only.
I have attached a raw screenshot here :
http://img51.imageshack.us/img51/4430/uploadm.jpg
As the first step, the page loads an empty structure with no product detials in it.
Then using javascript BigPipe, it adds details of products in the structure.
The Product Detail Structure :
<div class="product_disp"
onclick="return clickEffect(this,event);"
onmousemove="return show_img_trail('product_details');"
onmouseout="return hide_img_trail(this);" align="left" >
<img src="pic.jpg" class="prodcuts_img"/>
<span style="overflow:hidden;" align="left"> <b> Product_3 </b> <br/>
id : 8146 <br /></span>
<span style="padding:0px;width: 100%;" align="right">Available </span>
</div>
But when i try to scroll down the scroller for product_details <div> , it scrolls slowly.
what can i do to make scroll like normal?
i dont know what exactly making it slower.

There are a lot of options, and they might not all be applicable, but here are some:
Don't load 10,000 items on a single page, instead opting to load maybe 100 and then allowing users to page through (either using a traditional page selector, or with a "load more" link when they hit the bottom, or even autoloading more as they scroll to the bottom).
Move JavaScript event bindings for any events that bubble from the individual elements to the parent, then handle them there. To do this easily, use jQuery.live('event', function(){ ... });.
Use a stylesheet instead of putting styles inline. And make sure that your selectors are high-performance (don't over-qualify them, prefer IDs and a class to adding long chains of element names, etc.).
Generally speaking (it doesn't appear you're doing this) avoid CSS3 effects like drop shadows until they become more performance-friendly.
Make sure you're not executing excessive JavaScript queries (cough, using onscroll or using onmouseover for every element on the page, cough).
Without seeing what you're doing in your JavaScript and what your CSS looks like, it's hard to give you more specific details about your situation, though.

The best idea is to give a full test page or URL if you want specific answer for your case.
You can keep 10 000 products in memory (as a Javascript object) without displaying all of them as a part of your page. It makes layout computation much faster. Try listing in groups of 10-20-30 items or adding/removing them on scroll event.
Use event delegation to improve performance (a root element handles all the events)
function normalize(e) {
e = e || window.event;
e.target || (e.target = e.srcElement);
return e;
}
var root = document.getElementById("root");
root.onclick = function(e) {
e = normalize(e);
return clickEffect(e.target, e);
}
root.onmouseout = function(e) {
e = normalize(e);
return hide_img_trail(e.target);
}
Use mouseover instead of mousemove (delegated as well)
root.onmouseover = function(e) {
return show_img_trail('product_details');
}
Separate presentation (CSS) from markup (HTML). It won't affect performance, but makes your code readable and maintainable.

I ran across similar problem few days a go! What kind of other creative interface we possible can provide in there?
Currently i am using event delegation on my page but i am quite curious about other possible interfaces in such scenarios. Pagination or load more are not an options in my case so what else i can do there?

Related

Can this popup feature be applied for many users?

I made a popup feature, which shows the phone number of a user. I was able to apply this feature to one instance. A single user.
Normally, each user has a unique phone number. Each user's number's already embedded, it's just to reveal the numbers, for multiple users.
But then, I thought, what if I have lots of users as they come, to the site? How do I dynamically apply the same popup feature without writing the same lines of code I wrote for the single user, over and over again?
Please, help me out.
This is the JavaScript I wrote...
let tansform_scale_0 = document.querySelector('.transform_scale_0');
let num_btn = document.querySelector('.num_btn');
num_btn.addEventListener('click', ()=>{
if (!tansform_scale_0.classList.contains('scale_to_1')) {
tansform_scale_0.classList.add('scale_to_1');
} else {
tansform_scale_0.classList.remove('scale_to_1');
}
})
Please view the code here: https://codepen.io/matthewdon/pen/MWQEvJM
You need to extend the logic you've applied to each of your cards. For example, the simplest way is to use querySelectorAll rather than the querySelector you currently have.
This is very similar in that it will return you a list of matching elements which you can then loop over and add your event listeners to in much the same way you are doing now.
However to make things a bit easier, you will be better off looping over each of the containing .card elements first. That way you can scope a second querySelector to the containing element and leave the rest of your logic largely intact.
You can shortcut the click handler itself though, by using classList.toggle rather than manually checking the class and then adding/removing it as required.
const cards = document.querySelectorAll('.card');
cards.forEach((card) => {
// rest of your click handler logic
})
Here's a snippet that brings all that together. I've put it on codepen as the editor on here isn't really suited to such a large amount of html: https://codepen.io/29b6/pen/VwQQqrw?editors=1111

Toggling an html IMG element's class using JS (no Jquery)

I give up... All of your answers were just different ways of targeting the local element.
If you bothered to actually read what I was saying you would realise that it was not a problem with the code I already had, just that the code DID NOT work on IMG tags.
While faffing around trying to demonstrate my problem (and that none of your solutions did anything different to what was already happening) I found that I can achieve exactly what I want by applying a Grayscale filter to a DIV element placed over each image. The mouseover event then triggers an opacity change in the DIV element.
It is a little heavier that I wanted but it answered my ACTUAL question. The answer being:
Yes, there probably is a way to toggle class of IMG tags. But no, I am probably not going to find it here without causing arguments or being told i'm using "bad code". So yes, it IS easier and more efficient to target DIV elements.
By the way, page load times are about how large data packages are. Larger data packages (images, html/css/js documents, etc) take longer to download and so the page takes longer to load. The website I am trying to create proves this thesis, I have an almost complete and (almost) fully functional website with loads of 'clever' little effects all under 20mb, about 15mb of which is images. This website is clean and simple, is hosted on my Samsung Galaxy Tab 4 (using Papaya) and loads almost instantly.
THIS is what I meant by "I want this to be VERY lite". Thank you all for your attempts to help, it's just a shame that I couldn't get anyone to understand what was going on.
If you add onClick to image element you don't need to pass anything, you will receive MouseEvent which contains all information. You need target from event.
I suggest to not use onClick on element as it is not scalable, you have to add it to all elements. Better to add listener to wrapping/container element and then filter target by some attribute e.g data-something Please check fiddle
So you have wrapping element and you images:
<div class="images-container">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray thumb-color" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
</div>
and you attach listener to you wrapping element. It is best practice as you don't attach listeners to each element and same time you are able easily scale your solution
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('click', function(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
});
The same code can be extended to support mouseover and mouseout. Check fiddle2. One function to rule them all and in the darkness bind them..
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('mouseover', onToggleImage);
imagesContainerEl.addEventListener('mouseout', onToggleImage);
function onToggleImage(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
}
Also updated fiddle which shows how to make image grayscale/color
Is what you refer to in your question as
onClick="colorFunction(image1)"
an inline javascript event listener?
If so, try replacing it with:
onClick="colorFunction(this)"
and rewrite colorFunction() as:
function colorFunction(image) {
image.classList.toggle('thumb-color');
}

Assign links and classes in JavaScript

I have a site that is in English and Spanish, and in each page of the site there is a link that leads to the Spanish version of that specific page, so if the user were on the "home.php" page, it would look like this:
<div id="language">
<ul class="language">
<li class="english"></li>
<li class="divider"></li>
<li class="spanish"></li>
</ul>
</div>
What I would like to do is leave the href and the class in the <a> tags in the HTML blank and assign a class and an href URL to the <a> depending on the page the user is on, that way I could, for example, just add that language div to an external file, and use an <include> to attach it to each page. To accomplish this I'm using the following code:
$('ul.menubar a').each(function(){
if(location.href.match('home.php')){
$('ul.language li.english a').addClass('active');
$('ul.language li.english a').append(function() {
$(this).attr('onclick', 'return false;');
});
$('ul.language li.spanish a').addClass('notactive');
$('ul.language a[href!="home.php"]').append(function() {
$(this).attr('href', 'inicio.php');
});
}
}
The problem is that the English version of the site has 4 links in the navigation bar (home.php, services.php, aboutus.php, contact.php), and the Spanish version likewise (with the corresponding translation of the URL names). I think that having to repeat that code 8 times (1 for each link, 4 links in each language) would be excessive and would actually add more code than simply adding the class and href url in the HTML. The point of using JS would be to simplify things.
So I basically would like to know if anyone can think of a better way to do this, that wouldn't require that much code. I'm trying to avoid having to, in the event that I'd need to change something, have to edit each different page. Also, I would like to know if this is the best way to achieve want I want to do using JavaScript.
HTML is best suited for managing content. CSS is best suited for presenting that content, and JavaScript is best suited for determining how that content behaves. Instead of trying to inject links and control the HTML from JavaScript; instead, leave the content where it belongs, inside the HTML, and use JavaScript to define one or two event-handlers to take action based on the class values on the hyperlinks themselves.
You already have a class on your English hyperlinks, and a separate class on your Spanish hyperlinks, so you can use this to your advantage.
Writing the Click Handlers:
Since toggling your "Language switch" most likely causes a boolean value to be set, you can use two click handlers to target all of your English links and all of your Spanish links, and then control the behavior based on the value of that switch at the time the links are clicked.
// handler for all English links
$('li.english a').click(function(event) {
event.preventDefault();
if(/* Switch is english */) {
window.location = $(this).attr("href");
}
});
// handler for all Spanish links
$('li.spanish a').click(function() {
event.preventDefault();
if(/* Switch is SPANISH */) {
window.location = $(this).attr("href");
}
});
Note that when a link is clicked, we first check the switch. Depending on it's value, we either redirect to that hyperlink, or simply prevent the default behavior -- going to a new page -- from completing.
Handling the Presentation:
Now, your other problem is going to be that, assuming your Spanish site and your English site are one in the same, you'll now see 8 hyperlinks in total. Again, this is where your switch can come in handy.
// single handedly hide or display the relevant content, based on the switch
function switchToEnglish() {
$('.english').show();
$('.spanish').hide();
}
function switchToSpanish() {
$('.spanish').show();
$('.english').hide();
}
Now, I don't know what else is contained in your switch function, but the general idea here is that we don't need to modify the content. We just need to show and hide the content. You'd need to integrate this concept into your existing switch function, if you don't already have something like this in place.
There are several advantages in this approach:
Your Web designers will still see href's in the HTML and can read and understand the HTML without needing your help or needing to go and look at JavaScript code. Not only will they see familiar patterns that they're used to seeing, but you'll likely have a better working relationship with them.
Search engines spidering your site will be able to read the links and follow them.
Browsers without JavaScript will be able to process the links. Some people seem to care about this. I don't. But it's worth mentioning anyway.
In summary, you're right about it being easier to manage in HTML. By using this technique, you can eliminate the repetition in the code that you're rightfully concerned about, and also move the content back to the HTML, as your gut is telling you is the correct thing to do. Not only will your code be more readable, but you'll get better SEO results as well.

Best way to rearrange positioning of images/divs with javascript/jquery?

I took a peek at the source of http://wonderwall.msn.com and noticed how all the span tags that the blocks of the wall have don't seem to be associated with any ID. It makes me very curious how they are able to accomplish the animated repositioning of elements when you click on one of the blocks/images without associated ID.
I am curious how you can click on say an image and get other images around it to move to the side. Is it some sort of formula or algoirthm?
I would like to accomplish getting say, 5 spans/blocks, clicking on one, and getting others to animate/move to the sides.
IDs are not necessary and often harmful. You don't need them, generated or otherwise.
When you put an element on a page with an ID, you're making the claim that there should be only one of whatever it is. Seldom is this true. More often, what you want to do is associate some behavior with some of the elements on the page, of which there may be many, one or zero.
In this case, there are lots of little image dealies, which when clicked, rearrange themselves. I don't have an algorithm for you for calculating how they should move, but here's a framework for how you could achieve the same with jQuery.
// create jQuery plugin for highlighting and shuffling brick dealies
(function($){
function expandify() {
var href = this.attr('href');
// create a popup containing the href
return this;
}
function shuffle() {
this.each(function(index, elem){
// calculate new position and move the element there.
});
return this;
}
$.fn.expandify = expandify;
$.fn.shuffle = shuffle;
})(jQuery);
// attaches behaviors to elements on the page after they've loaded
// either $.ready, or window onload, or after some ajaxing takes place
$('.wallBrick')
.click(function(e){
$(e.target)
.expandify();
$('.wallBrick')
.not(e.target)
.shuffle();
});
The IDs are generated via JavaScript on-the-fly. You won't see it in the source, but you'll see it if you inspect it with Firebug.

jQuery Graceful Degradation

I want to spruce up some areas of my website with a few jQuery animations here and there, and I'm looking to replace my AJAX code entirely since my existing code is having some cross-browser compatibility issues. However, since jQuery is a JavaScript library, I'm worried about my pages not functioning correctly when JavaScript is turned off or doesn't exist in a user's browser.
I'll give an example: Currently, I'm using a pure CSS tooltip to give my users (players, the site is a browser game) information on other users. For example, if the other players in the game satisfy one or more conditions, a target icon is displayed next to their name, and upon hovering over that target icon information regarding the reasons behind the target is displayed. This is useful information, as it helps my players to know who they should plan to attack next in the game.
Currently, I do such tooltips using CSS. I have a parent div that holds the image of the target icon of class "info". I then have a div inside of that with class "tooltip" that, on the hover state of the "info" class that it is contained in, is shown, but on the normal state is hidden. I thought it was rather clever when I read about it, and since no JavaScript is used it works on any CSS compliant browser.
I would like to use jQuery to achieve the same effect, mostly because it would look much cleaner, but also because I believe quick and subtle animations can make such things "randomly appearing" make a lot more sense to the user, especially on the first encounter. I'm just wondering if the two will conflict. This is only one example of this, there are numerous other examples where the inability to use JavaScript would hinder the site.
So what I'm asking I guess is, how does one make a jQuery site degrade gracefully on browsers that do not support JavaScript, but otherwise do support most CSS? My goal is for the site to function on a basic level for all users, regardless of choice in browser. The animation is a good example, but I'm also worried about the more dynamic bits, like the auto-updating with AJAX, etc. Are there any good resources on how to achieve this, or do you have any advice about the best way such degradability could be achieved?
Thanks
PS: Totally irrelevant, but Firefox seems to think that "degradability" isn't a word, but "biodegradability" (with the "bio" prefix) is. Weird...
If you consider the "Cascading Order" of css, could you not just add a css style at the very end of all your previous css definition in order to cancel any css effect you currently have for tooltip effect ?
That css rule would only be declared if Javascript is activated and JQuery detected.
That way, you are sure your css tooltip effect is not in conflict with your JQuery effect.
Something like:
a.info:hover span{ display:none}
with the use of "js_enabled" class to make this css rule conditional.
You also can do it by adding css rule on the fly:
function createCSSRule(rule,attributes)
{
//Create the CSS rule
var newRule = "\n"+rule+"{\n";
for (var attribute in attributes)
{
newRule += "\t" + attribute + ": " + attributes[attribute] + ";\n";
}
newRule += "}\n";
//Inject it in the style element or create a new one if it doesn't exist
styleTag = $E('style[type="text/css"]') || new Element("style").setProperty('type','text/css').injectInside(document.head);
if(window.ie)
{
styleTag.styleSheet.cssText += newRule;
}
else
{
styleTag.appendText(newRule);
}
}
The most simple solution for Separation of CSS and Javascrip is to remove your css class
function jscss(a,o,c1,c2)
{
switch (a){
case 'swap':
o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): <-
o.className.replace(c1,c2);
break;
case 'add':
if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
break;
case 'remove':
var rep=o.className.match(' '+c1)?' '+c1:c1;
o.className=o.className.replace(rep,'');
break;
case 'check':
return new RegExp('\\b'+c1+'\\b').test(o.className)
break;
}
}
This example function takes four parameters:
a
defines the action you want the function to perform.
o
the object in question.
c1
the name of the first class
c2
the name of the second class
Possible actions are:
swap
replaces class c1 with class c2 in object o.
add
adds class c1 to the object o.
remove
removes class c1 from the object o.
check
test if class c1 is already applied to object o and returns true or false.
If something can be done completely in CSS I say keep it that way. If lack of javascript in the browser is a concern, then most of the time I show the entire page unaffected.
Say for instance I'm going to use jQuery to toggle an element when a checkbox is clicked. On page load I look at the checkbox and update the element accordingly. If javascript is not enabled the element will still appear and the site will still be usable. Just not as nice.
Man, you have a browser-based game, right? You have less than 1% users with JS disabled! And that 1% is the apocalyptic number because I can BET that you have less than that ;)
Anyhow, if you are really concerned about this, just do the site without any JavaScript. And make it functional 100%. After your site works completely without any JS flavour, just start to improve with jQuery (or any other library; jQuery is the best :P ). But with careful: do not change ANY of you HTML. It's easier than it looks ;)
And yes, if you have things that work without JS (like those tooltips) keep it!

Categories

Resources