jquery performance issues by enable drag & drop for new elements - javascript

I've a small webapplication that works with some drag / drop functionality. Just imagine a small order system in which you can say order 1 (draggable) will be done by employee 2 (droppable). That works fine. BUT:
Every 20sec. I ask the database via AJAX for new orders. These new orders will also be draggable. In case that another college has given an order to en employee the list of orders for every employee is also no loaded. To enable drag / drop after the ajax request I had to run:
$('.order').draggable({
..
});
and
$('.employee').dropable({
..
});
So the jquery function walks every 20 secunds through the hole DOM. After 10-15 minitues the app becomes very slow. Do you have an idea how to ingrease that process? Is it possible to give an absolute statement that every .order class is draggable even if this element will be create after the first registration?

I think the problem is that the elements that are already on the page become draggable over and over again.
I think a solution would be to assign a class to those that already have it:
$('.order').each(function() {
var element = $(this);
if ( !element.hasClass('event-already-attached')) {
element.addClass('event-already-attached').draggable({
})
}
});

Thanks # Jonas your great idea did it!
You can use the classes ui-droppable and ui-draggable for that job
$('.order').each(function() {
var element = $(this);
if ( !element.hasClass('ui-droppable')) {
element.droppable({
...
}
});

Related

Next/Prev buttons to step through div contents

First of all a disclaimer, I'm not a dev. I'm halfway through The Odin Project and have covered some HTML and CSS, but, have not yet started on JS. In order to help with my learning I've created my own blog. My aim is for each blog post to have its own stylesheet (so with each new post I learn a little more about CSS).
Anyway, I plan to write a post about the benefits of using an eReader, specifically the Kindle. I've styled the page to look like a Kindle Oasis, and I'd like the reader to be able to step through the article contents via the Kindle's next/prev buttons, but, as I'm not a dev, this is where I'm stuck. Via Stack overflow I've managed to add some JS that will display page 1, 2 and 3 via dedicated buttons for each dive element, but, what I really need is to step through x number of pages via the prev/next buttons.
Here's what I have so far: https://codepen.io/dbssticky/pen/yLVoORO. Any help would be much appreciated. What I should do of course is finish The Odin Project and come up with a solution on my own, but, I'd really like to get this Kindle article published sooner rather than later. Hence my rather cheeky request for assistance.
Here's the JS I'm currently using:
function swapContent(id) {
const main = document.getElementById("main_place");
const div = document.getElementById(id);
const clone = div.cloneNode(true);
while (main.firstChild) main.firstChild.remove();
main.appendChild(clone);
}
You have the right idea and it just needs a few adjustments to get the previous/next functionality.
Currently your div IDs are following the format operation1, operation2, and so on. Since you want the previous/next functionality you'll need to change your 'swapping' function, which currently takes the full ID, to use the numeric portion only.
Add a new function which appends the number to 'operation' instead of using the whole thing:
function goToPage(pageNumber){
const main = document.getElementById("main_place");
const div = document.getElementById("operation" + pageNumber);
const clone = div.cloneNode(true);
while (main.firstChild) main.firstChild.remove();
main.appendChild(clone);
}
And then change your Page 1/2/3 buttons to use goToPage(1), goToPage(2) and so on.
Now for the previous/next functionality you'll need a way to track which page you're on, so that you can figure out which page to load.
Add a variable at the top (outside functions)
var currentPage = 0;
Then add a line in your goToPage function to track the page you're on.
currentPage = pageNumber;
Now that you're tracking you can add a previous and next function.
function goNextPage(){
goToPage(currentPage-1);
}
function goPreviousPage(){
goToPage(currentPage+1);
}
Then call it from the previous and next buttons.
<button onClick="goNextPage()" class="next-button"></button>
<button onClick="goPreviousPage()" class="previous-button"></button>
Here's a codepen: https://codepen.io/srirachapen/pen/WNZOXQZ
It's barebones and you may have to handle things like non existent div IDs.
HTML
<button class="next-button" onclick="nextContent()"></button>
<button class="previous-button" onclick="prevContent()"></button>
JS
var pageid = 0;
var maxpage = 3;
function nextContent() {
if(pageid == maxpage) return
pageid++
swapContent(`operation${pageid}`)
}
function prevContent() {
if(pageid == 1) return
pageid--
swapContent(`operation${pageid}`)
}
you can try this to switch between pages. But you may need to edit the "swapContent" method more sensibly.
Track the Current Page
Whatever solution you use to render pages & links (manual hardcoded links & content vs externally-stored & auto-generated), one thing is unavoidable: You need to track the current page!
var currentPage = 0
Then, any time there's a page change event, you update that variable.
With the current page being tracked, you can now perform operations relative to it (e.g. +1 or -1)
I'd suggest making a goToPage(page) function that does high-level paging logic, and keep your swapContent() function specifically for the literal act of swapping div content. In the future, you may find you'd want to use swapContent() for non-page content, like showing a "Welcome" or "Help" screen.
Example:
function goToPage(page) {
// Update `currentPage`
currentPage = page
// ... other logic, like a tracking event or anything else you want you occur when pages change
// Do the actual content swap, which could be your existing swapContent()
swapContent('operation'+page)
}
You'd invoke the function like so:
goToPage(3) // Jump to a specific page
goToPage(currentPage + 1) // Go to the next page
goToPage(currentPage - 1) // Go to the prev page
You can make separate helper functions like "goToNextPage()" if you desire, but for sure you start with a fundamental page-change function first.

jquery slide menu - better way?

I'm pretty new to javascript/jquery and I just built a simple slide menu.
It has 3 menus and each menu has a submenu...everything is working fine, I just want to know if there's a better way to accomplish the same task.
Here's my js code:
function menuOpen(menu){
if(menu=='menu1'){
$("#sub2").slideUp(400);
$("#sub3").slideUp(400);
$("#sub1").slideToggle(400);
}else if(menu=='menu2'){
$("#sub1").slideUp(400);
$("#sub3").slideUp(400);
$("#sub2").slideToggle(400);
}else if(menu=='menu3'){
$("#sub1").slideUp(400);
$("#sub2").slideUp(400);
$("#sub3").slideToggle(300);
}
}
without seeing your HTML:
LIVE DEMO
function menuOpen(menu){
var num = menu.match( /\d+/ ); // Regex expression to retrieve the Number
$('[id^=sub]').slideUp(); // slide UP all ID starting with sub
$('#sub'+num).slideToggle(); // get the desired ID :)
}
Use of jQuery means that we want to easily manipulate DOM elements , which means that without seeing a HTML sample of your DOM nodes and structure you're about to target it's hard to make the above even simpler.

Autodividers listview with collapsable option

I am working on a listview which has auto dividers based on date it is a very long list & data-autodividers='true' works fine but I want to further improve it by making the listview collapsible on date.
This can be done from back-end using c# (I am working on an asp.net webform mobile website) where I group my list based on Month-Year and make each group collapsible.
But I would love to do it with jQuery as I do for autodivider. I have set up same on jsFiddle.
http://jsfiddle.net/5PnBT/10/
How can I make these auto-divider collapsible using jQuery without doing it from code-behind file (c#)?
I did not see where jquerymobile has this as a build in option.
$(document).on("pageinit", "#page-wrapper", function () {
$("#hp-latest-articles").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr('date');
return out;
}
}).listview('refresh');
});
If I have understood your problem, I think you just have to use the $.mobile.listview.prototype.options.autodividersSelector option. I had a similar problem, so if you need to list them according to the date attribute on the single element, do:
$( document ).on( "mobileinit", function() {
$.mobile.listview.prototype.options.autodividersSelector = function( element ) {
return (element.attr('date'))
};
});
I prepared a jsbin for that: http://jsbin.com/enuwoj/1/edit
There are two solutions to your problem.
Either you use the collapsible list sets on the jQuery Mobile side, then you will be able to reach exactly what you are looking for. You might nee to edit the looks of the element using CSS to make it look like a listview.
http://jsfiddle.net/rc9Gk/
<div data-role="collapsible">
<h3>Title</h3>
<ul><li>Item1</li><li>Item2</li></ul>
</div>
Second solution would be to apply custom event handlers on click event of the listview control. Whenever a click event occurs on a list divider you can hide the following list elements till the next auto-divider. This solution needs a bit of coding. If this solution fits you, I can write that code for you do let me know.
I believe your problem is solved by adding the following to the bottom of your original fiddle
$('.ui-li-divider').click( function(ev ){
var li = $(ev.target).next(':not(.ui-li-divider)');
while ( li.length > 0 ) {
li.toggle();
li = li.next(':not(.ui-li-divider)');
}
});
Here is the updated jsFiddle
Basically, everytime you click a divider, it looks for all following LIs until the next divider and toggles their visibility.
You'll need either <div data-role="collapsible"> or <div data-role="collapsible-set">, depending on if you wanted to group them or not.
If you want them pre-collapsed by default, include the data-collapsed="true" attribute as well.

jquery checkbox slow, not sure how to fix

I have used firebug and IE profilers and can see what function in my code is causing the slowness. Being new to jquery, the recommendations that I have read online are not clear to me. I have made an example page that shows the slow behavior when you check or uncheck a check box. No surprise that this is fast using Chrome.
The function that is slow can be found on line 139.
$('.filters input').click( function()
JSFiddle can be found here
The code is 122 KB and can be found here
UPDATE: if you know of any examples online that are similar in function and faster, please share.
i had a brief look through your code, but it was very hard to follow. it seemed as if you were looping through things many many times. i used a much simpler approach to get the list of all states.
your approach was
* make a massive string which contained every class (possibly repeated multiple times)
* chop it up into an array
* loop through the array and remove duplicates
i simply took advantage of the fact that when you select something in jQuery you get a set rather than a single item. you can therefore apply changes to groups of object
$(document).ready(function () {
//this will hold all our states
var allStates = [];
//cache filterable items for future use
var $itemsToFilter = $(".filterThis");
//loop through all items. children() is fast because it searches ONLY immediate children
$itemsToFilter.children("li").each(function() {
//use plain ol' JS, no need for jQuery to get attribute
var cssClass = this.getAttribute("class");
//if we haven't already added the class
//then add to the array
if(!allStates[cssClass]) {
allStates[cssClass] = true;
}
});
//create the container for our filter
$('<ul class="filters"><\/ul>').insertBefore('.filterThis');
//cache the filter container for use in the loop
//otherwise we have to select it every time!
var $filters = $(".filters");
// then build the filter checkboxes based on all the class names
for(var key in allStates) {
//make sure it's a key we added
if(allStates.hasOwnProperty(key)) {
//add our filter
$filters.append('<li><input class="dynamicFilterInput" type="checkbox" checked="checked" value="'+key+'" id="filterID'+key+'" /><label for="filterID'+key+'">'+key+'<\/label><\/li>');
}
}
// now lets give those filters something to do
$filters.find('input').click( function() {
//cache the current checkbox
var $this = $(this);
//select our items to filter
var $targets = $itemsToFilter.children("li." + $this.val());
//if the filter is checked, show them all items, otherwise hide
$this.is(":checked") ? $targets.show() : $targets.hide();
});
});
FIDDLE: http://jsfiddle.net/bSr2X/6/
hope that's helpful :)
i noticed it ran quite a bit slower if you tried to slideup all the targets, this is because so many items are being animated at once. you may as well just hide them, since people will only see the ones at the top of the list slide in and out of view, so it's a waste of processor time :)
EDIT: i didn't add logic for show all, but that should be quite a trivial addition for you to make if you follow how i've done it above
You could use context with your selector:
$('.filters input', '#filters_container').click(function()...
this limits the element that jQuery has to look in when selecting elements. Instead of looking at every element in the page, it only looks inside your $('#filters_container') element.

Tree Menu? In JS?

I need a tree menu. But instead of a listview where you expand/collapse i need a dropdown box with the list and when you click on a element i need the box to update (with the first entry being 'Back') so the menu stays in a neat little dialog.
Does this menu have a name? Does anyone know where i can get code to do this?
I can think of several jQuery plugins which would soot your purposes. However, I would recommend jQuery iPod Style Drilldown Menu (Newer Version), which is exactly what it sounds like. The dropdown box updates in place, uses a cool sideways slide animation, and includes a "Back" button (as you desired). Finally, if you don't want any animation, you can try tweaking the plugin's many options. Setting crossSpeed to 0 may work, for example.
Adam is right, jQuery offers an assortment of menu's which you could use. Really though, this is a somewhat trivial problem, the code to write it would take up about 1/10th the space that jQuery's code will. So if possible I would say write it without jQuery.
The most effective method would be to do it JS OOP (Javascript Object-Oriented), but understandably this is a confusing topic.
Basically you just want something like:
function drillDown(){
//Any code that multiple drilldowns
// might need on the same page goes here
//Every instance of a drillDown will
// instantiate a new set of all functions/variables
// which are contained here
//A reference to the parent node the dropdown is placed in
this.parent;
//A reference to the div the dropdown is incased in
this.object;
//Returns a reference to this object so it can be
// stored/referenced from a variable in it's
// superclass
return this;
}
//Prototype Functions
//prototypes are shared by all
// instances so as to not double up code
//this function will build the dropdown
drillDown.prototype.build = function(parent){
//Too lazy to write all this, but build a div and your select box
// Add the select box to the div,
// Add the div to the parent (which is in your document somewhere)
var divEle = document.createElement('div');
var inputBox = document.createElement('input');
//code code code
divEle.appendChild(inputBox);
parent.appendChild(divEle);
}
//this function loads the newest dataset of
drillDown.prototype.loadNewDataSet = function(data){
//first clear out the old list
// remember we have a reference to both the
// 'object' and 'parent' by using
// this.object and this.parent
//load the data, we are going to use the text from
// the select boxes to load each new dataset, woo eval();
// If you didn't know, eval() turns a string into JS code,
// in this case referencing an array somewhere
var dataSet = eval(data);
//then loop through your list adding each new item
for(item in dataSet){
//add item to the list
//change the .onClick() of each one to load the next data set
// a la ->
selectItem.onClick = function(){this.loadNewDataSet(item);};
//if you name your datasets intelligently,
// say a bunch of arrays named for their respective selectors,
// this is mad easy
}
}
//Then you can just build it
var drillDownBox = new drillDown();
drillDownBox.build(document.getElementsByTagName('body')[0]);
drillDownBox.loadNewDataSet("start");
//assuming your first dataset array is named "start",
// it should just go
And by the way, Adam also said it, but wasn't explicit, this is refered to as a drill-down.

Categories

Resources