I did a search form that can navigate between the results using the arrows up and down key. But only works with the first results, if you want to navigate again you need to focus on the search input text again, I can't navigate pressing up or down again if i don't do this.
JSFiddle: http://jsfiddle.net/gaw7g332/6/
Js code:
/* JS File */
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('.buscar-icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").on("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('p#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('p#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
$("input#search").on("keydown", function(e) {
var $listItems = $('ul#results li');
var $listItemsa = $('ul#results li a');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
if ( key != 40 && key != 38 ) return;
$listItems.removeClass('selected');
if ( key == 40 ) // Down key
{
if ( ! $selected.length || $selected.is(':last-child') ) {
$current = $listItems.eq(0);
event.preventDefault();
}
else {
$current = $selected.next();
event.preventDefault();
}
}
else if ( key == 38 ) // Up key
{
if ( ! $selected.length || $selected.is(':first-child') ) {
$current = $listItems.last();
event.preventDefault();
}
else {
$current = $selected.prev();
event.preventDefault();
}
}
$.fn.focusWithoutScrolling = function(){
var x = $(document).scrollLeft(), y = $(document).scrollTop();
this.focus();
window.scrollTo(x, y);
return this; //chainability
};
var $currenta = $current.children();
$currenta.focusWithoutScrolling();
$current.addClass('selected');
event.preventDefault();
});
That is because your event listener is only checking the key event on the input field you can add the list of results to the listener like this:
$("input#search, #results").on("keydown", function(e) {
.....
});
This should allow to navigate the results
fiddle
Related
the code does not allow me to update/edit the name in each text box. I've reviewed the code several times but could not find any errors. Grateful for any help. Thanks.
THE HTML
/*
* Confirm category deletion
*/
$("body").on("click", "a.delete", function () {
if (!confirm("Confirm page deletion")) return false;
});
/////////////////////////////////////////////////////////
/*
* Rename Category
*/
var originalTextBoxValue;
$("table#pages input.text-box").dblclick(function () {
originalTextBoxValue = $(this).val();
$(this).attr("readonly", false);
});
$("table#pages input.text-box").keyup(function (e) {
if (e.keyCode == 13) {
$(this).blur();
}
});
$("table#pages input.text-box").blur(function () {
var $this = $(this);
var ajaxdiv = $this.parent().find(".ajaxdivtd");
var newCatName = $this.val();
var id = $this.parent().parent.attr("id").substring(3);
var url = "/admin/shop/RenameCategory";
if (newCatName.length < 2) {
alert("Category name must be at least 2 characters long.");
$this.attr("readonly", true);
return false;
}
$.post(url, { newCatName: newCatName, id: id }, function (data) {
var response = data.trim();
if (response == "titletaken") {
$this.val(originalTextBoxValue);
ajaxdiv.html("<span class='alert alert-danger'>That title
is taken!</span>").show();
} else {
ajaxdiv.html("<span class='alert alert-success'>The category name has been changed!</span>").show();
}
setTimeout(function () {
ajaxdiv.fadeOut("fast", function () {
ajaxdiv.html("");
});
}, 2000);
}).done(function () {
$this.attr("readonly", true);
});
});
///////////////////////////////////////////
});
</script>
\\\
I am using infinite scroll to load posts and tried to integrate a custom like button for every single posts that needs a small jquery script to work. My problem is I added this Jquery directly after the sucess in ajax load posts. But when I load eg the 3. page my jquery script executes twice and on the posts of the 2nd page the lke buttons are not working correctly. How can I handle this? If I dont execute the code after the ajax request and only call this jquery code globally the like buttons do not work in the new loaded posts of the ajax infinite scroll. Maybe I need to stop the sript of before when eg loadin 3. page through the ajax infinite scroll but how? This is my code:
function load_more_posts(selector){
var url = $(selector).attr('href');
var data;
loading = true;
$.ajax({
url: url,
data: data,
success: function( data ) {
var $items = $( '.loading-content .item', data );
$new_anchor = $( selector, data );
$items.addClass('hidden');
if ( $('#cooked-plugin-page .result-section.masonry-layout .loading-content').length ){
$( '.loading-content').isotope( 'insert', $items );
} else {
$( '.loading-content').append($items);
setTimeout(function() {
$items.removeClass('hidden');
}, 200);
}
if($new_anchor.length) {
$(selector).attr('href', $new_anchor.attr('href'));
} else {
$(selector).remove();
}
loading = false;
$('.like-btn').each(function() {
var $button = $(this),
$icon = $button.find('> i'),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id');
cookied = $button.attr('data-cookied');
userLiked = $button.attr('data-userliked');
if ( cookied == 1 && typeof likedRecipes !== 'undefined' && likedRecipes.split(',').indexOf(recipeID) > -1 || userLiked == 1 ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
}
});
$('#cooked-plugin-page .like-btn').on('click', function() {
var $button = $(this),
$icon = $button.find('> i'),
$count = $button.find('.like-count'),
count = parseInt($count.text()),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id'),
cookied = $button.attr('data-cookied'),
likeURL = $button.attr('href'),
likeAction;
if ( $icon.hasClass('fa-heart-o') ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
count++;
if (cookied == 1){
if ( typeof likedRecipes === 'undefined' ) {
likedRecipes = recipeID;
} else {
likedRecipes = likedRecipes + ',' + recipeID;
}
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
}
likeAction = 'like';
} else {
$icon.removeClass('fa-heart').addClass('fa-heart-o');
count--;
if (cookied == 1){
if ( typeof likedRecipes === 'undefied' ) {
return false;
}
}
if (cookied == 1){
var likedSplit = likedRecipes.split(','),
recipeIdx = likedSplit.indexOf(recipeID);
if ( recipeIdx > -1 ) {
likedSplit.splice( recipeIdx, 1 );
likedRecipes = likedSplit.join(',');
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
likeAction = 'dislike';
}
} else {
likeAction = 'dislike';
}
}
$.ajax({
'url' : likeURL,
'data': {
'action' : 'cp_like',
'likeAction': likeAction
},
success: function(data) {
$count.text(data);
}
});
return false;
});
$('#cooked-plugin-page .tab-links a').on('click', function() {
var tab = $(this).attr('href');
if ( !$(this).is('.current') ){
$(this).addClass('current').siblings('.current').removeClass('current');
$('#cooked-plugin-page.fullscreen .tab').removeClass('current');
$(tab).addClass('current');
$win.scrollTop(0);
}
return false;
});
if($('.rating-holder').length) {
$('.rating-holder .rate')
.on('mouseenter', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
$parent.addClass('rate-' + (my_index + 1));
})
.on('mouseleave', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
if(rated !== undefined) {
$parent.addClass('rate-' + rated);
}
})
.on('click', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
$('.rating-real-value').val(my_index + 1);
$parent.attr('data-rated', my_index + 1);
$parent.addClass('rate-' + (my_index + 1));
});
}
setTimeout(function() {
masonry();
}, 500);
}
});
}
There's a great plugin for scrolling. He has methods such as bund, unbind, destroy and e.t.c.:
https://github.com/infinite-scroll/infinite-scroll#methods
here i am trying to achieve infinite scrolling but what happens when i am scrolling too fast it fire multiple ajax request with same parameter , which cause same data again n again.how overcome from this problem pls help.
(function( $ ){
$.fn.scrollPagination = function(options) {
var opts = $.extend($.fn.scrollPagination.defaults, options);
var target = opts.scrollTarget;
if (target == null){
target = obj;
}
opts.scrollTarget = target;
return this.each(function() {
$.fn.scrollPagination.init($(this), opts);
});
};
$.fn.stopScrollPagination = function(){
return this.each(function() {
$(this).attr('scrollPagination', 'disabled');
});
};
var itr = 2;
$.fn.scrollPagination.loadContent = function(obj, opts){
var target = opts.scrollTarget;
var mayLoadContent = $(target).scrollTop()+opts.heightOffset >= $(document).height() - $(target).height();
if (mayLoadContent){
if (opts.beforeLoad != null){
opts.beforeLoad();
}
$(obj).children().attr('rel', 'loaded');
$.ajax({
type: 'POST',
url: opts.contentPage+"?iteration="+itr,
data: opts.contentData,
success: function(data){
itr++;
$(obj).append(data);
var objectsRendered = $(obj).children('[rel!=loaded]');
if (opts.afterLoad != null){
opts.afterLoad(objectsRendered);
}
}
});
}
};
$.fn.scrollPagination.init = function(obj, opts){
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
$(target).scroll(function(event){
if ($(obj).attr('scrollPagination') == 'enabled'){
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
});
//$.fn.scrollPagination.loadContent(obj, opts);
};
$.fn.scrollPagination.defaults = {
'contentPage' : null,
'contentData' : {},
'beforeLoad': null,
'afterLoad': null ,
'scrollTarget': null,
'heightOffset': 0
};
})( jQuery );
How about firing off the ajax every 10 times the scroll event is triggered?
$.fn.scrollPagination.init = function(obj, opts) {
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
target.scrollCount = 0;
$(target).scroll(function(event) {
this.scrollCount++;
if (this.scrollCount % 10 == 0) {
if ($(obj).attr('scrollPagination') == 'enabled') {
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
}
});
}
I used to call my ajax function when the scroll reaches the bottom of the page.
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$("#place_of_loading_image").show();
$.ajax({
url:'your source',
type: 'get',
dataType: 'script',
success: function() {
$("#place_of_loading_image").remove();
loading=false;
}
});
}
});
Background##
i am a complete noob with JS (i can slightly read it, but cant write it)
Problem
Link: http://s328792954.websitehome.co.uk//multi_step_form/
Im trying to make a multi-step form,
and i cam across a tutorial on-line which showed a basic example.
anyway.....
i've added a field for number only (example:loan amount)
but the coding i use is obviously wrong because now it will not accept any form of input
+ i think its interfering with the other coding.
the section starting with '//check if amount input is numbers' is the problem
Copy code
$(function(){
//original field values
var field_values = {
//id : value
'username' : 'username',
'password' : 'password',
'cpassword' : 'password',
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address',
'amountborrow' : '000'
};
//inputfocus
$('input#username').inputfocus({ value: field_values['username'] });
$('input#password').inputfocus({ value: field_values['password'] });
$('input#cpassword').inputfocus({ value: field_values['cpassword'] });
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
$('input#amountborrow').inputfocus({ value: field_values['amountborrow'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//check if amount input is numbers
var fields = $('#first_step input[type=amountborrow]');
var numOnly = /^[0-9]$/;
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='amountborrow' && !numOnly(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
//check if inputs aren't empty
var fields = $('#first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#username').val(),
$('#password').val(),
$('#email').val(),
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#age').val(),
$('#gender').val(),
$('#country').val(),
$('#amountborrow').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//send information to server
alert('Data sent');
});
});
please help
(sorry if this is wrong section i didnt really understand forum sections)
#edit#
#Banaan information was great :) THANKS!
but the form still accepts the incorrect info...
the 'field' doesnt but the form does and proceeds to the next step.
Do i need a }else return false somewhere?
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//check if amount input is numbers
var fields = $('#first_step input[type=amountborrow]');
var numOnly = /^[0-9]+$/;
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<3 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='amountborrow' && !numOnly.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
} else {
$(this).addClass('valid');
}
});
//check if inputs aren't empty
var fields = $('#first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
Pleas further Advise
You created some sort of a new RegExp object, which is the right direction, except you probably want to accept any number instead of only a single digit:
var numOnly = /^[0-9]+$/;
In which [0-9] means a digit, and + means one or more occurrences.
The way in which you use that RegExp object, however, is incorrect. if you look at the e-mail regular expression in the second step, they use
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var value = $(this).val();
emailPattern.test(value)
The emailPattern.test(value) part is what you missed. To check if the input is a number, you use not !numOnly(value) but !numOnly.test(value).
For a more complete tutorial on javascript regular expressions, you might want to take a look at W3Schools
Any general tips how to increase a longish js code like this? It works great but sometimes it gets a little sluggish and all the drag/drop and ajax features slow down.
I know this code is a little longer so I am not looking for specific suggestions. Just your first thoughts after taking a quick glance at this code.
EDIT:
I have found a pretty scary thing. The calls to dragDrop() are exponentially increasing in the $('.folderListOnclick').click event. After each click dragDrop() is called 1 time, 2 times, 4 times, 8 times. That's what's slowing it down.
But I don't understand why it is happening.
<script type="text/javascript">
//<!--
$(document).ready(function() {
function in_array (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true; }
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
var openedFolders = new Array();
var start = 0;
var stop = 0;
$('.drag').each(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width /*&& 30 == parseInt(width)*/) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
if (in_array($(this).attr('rel'), openedFolders)) {
$(this).addClass('ordinaryFolderOpened');
} else {
$(this).addClass('ordinaryFolderClosed');
}
}
if (in_array($(this).attr('rel'), openedFolders)) {
start = 1;
}
if (1 == start && stop < 2) {
if (30 == parseInt(width)) {
stop++;
}
} else {
start = 0;
stop = 0;
if (parseInt(width) > 30) {
$(this).parent().parent().hide();
}
}
});
function dragDrop()
{
$('.folders .trow1').hover(
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', "#C2E3EF");
}
},
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', 'transparent');
}
}
);
$('.drag').click(function() {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
} else {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width /*&& 30 == parseInt(width)*/) {
var isVisible = $next.is(':visible');
if (isVisible) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
} else {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderOpened');
}
clickedId = $(this).attr('rel');
clickedId = clickedId.split(',');
clickedType = clickedId[1];
clickedId = clickedId[0];
// $.ajax({
// type: 'POST',
// url: 'body/obsah/mediaManager/setOpenedFolder.php',
// data: 'id='+clickedId+'&type='+clickedType,
// success: function(msg){
// //alert(msg);
// }
// });
var start = 0;
var stop = 0;
var i = 0;
// close folder
if (isVisible) {
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
iteratedId = iteratedId.split(',');
iteratedId = iteratedId[0];
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if ($(this).css('width') > width) {
$(this).parent().parent().hide();
if ($(this).hasClass('ordinaryFolderClosed') || $(this).hasClass('ordinaryFolderOpened')) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
}
} else {
stop++;
}
}
i++;
});
}
// open folder
else {
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
iteratedId = iteratedId.split(',');
iteratedId = iteratedId[0];
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if (parseInt($(this).css('width')) == parseInt(width)+5) {
$(this).parent().parent().show();
}
if (parseInt($(this).css('width')) == parseInt(width)) {
stop++;
}
}
i++;
});
}
}
}
});
var dragId = 0;
var dragType = 0;
var dropId = 0;
var dropType = 0;
var isFile = false;
$('.drag').draggable({
revert: true,
cursorAt: {top: 0, left: 0},
drag: function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragType = dragId[1];
dragId = dragId[0];
}
isFile = false;
},
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('.drag2').draggable({
revert: true,
cursorAt: {top: 0, left: 0},
drag: function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragType = dragId[1];
dragId = dragId[0];
}
isFile = true;
}
});
$('.drop').droppable({
tolerance: 'pointer',
drop: function() {
if ($(this).attr('rel') !== undefined) {
dropId = $(this).attr('rel');
dropId = dropId.split(',');
dropType = dropId[1];
dropId = dropId[0];
if (dropId != dragId) {
if (false == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/mediaManager/folder_move.php',
data: 'nid='+dragId+'&pid='+dropId+'&ft='+dropType,
success: function(msg){
ajaxElementCall('left1', 'body/obsah/mediaManager/folder_list.php?type=1', 'right1', 'body/obsah/mediaManager/file_list.php?type=1&browse=0&assignType=0&CKEditorFuncNum=0&idFolder=0');
dragDrop();
}
});
} else if (true == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/mediaManager/file_move.php',
data: 'fid='+dragId+'&did='+dropId+'&ft='+dropType,
success: function(msg){
ajaxElementCall('right1', 'body/obsah/mediaManager/file_list.php?type=1&browse=0&assignType=0&CKEditorFuncNum=0&idFolder=0&reloadTree=0');
dragDrop();
}
});
}
}
}
}
});
}
dragDrop();
$('.folderListOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0&reloadTree=0';
ajaxElementCall('right1', 'body/obsah/mediaManager/file_list.php?type=1&'+append);
dragDrop();
$('.trow1').css('background', 'transparent');
$('.trow1').css('color', '#3e4245');
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
});
$('.folderEditOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0';
showModal('modal_div', 'Editácia adresára');
ajaxElementCall('modal_div', 'body/obsah/mediaManager/folder_edit.php?kam=edit1&'+append);
});
$('.folderDeleteOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0';
showModal('modal_div', 'Vymazanie adresára');
ajaxElementCall('modal_div', 'body/obsah/mediaManager/folder_delete.php?kam=del1&'+append);
});
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '0';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
id = id.split(',');
id = id[0];
}
});
ajaxElementCall('modal_div', '/body/obsah/mediaManager/folder_add.php?type=1&kam=new1&idFolder='+id+'&browse=0&assignType=0&CKEditorFuncNum=0');
});
}); //-->
</script>
Well you have not posted any of your HTML markup, and you have not posted the details of what the "ajaxElementCall" function does. Therefore it's hard to say exactly how you should fix the problem. It is true however that on every "drop" event, you end up calling the "dragDrop()" setup function again. You say that "ajaxElementCall" reloads some portion of the page, but your "dragDrop()" code always installs new event handlers on all ".drag" and ".drop" elements on the page. If "ajaxElementCall" only updates part of the page, then all the unchanged ".drag" and ".drop" elements will get additional event handlers piled on.
When you call .click() or .hover() for some selector, jQuery adds the event handler you supply to the set of handlers already registered. Thus, because you register new event handlers every time "dragDrop()" is called, you'll get more and more piled up. When an event happens, all of those handlers will be run.
Probably what you need to do is change "dragDrop()" so that you can tell it to only operate on a particular fraction of the page. Either that, or else when it runs it should "mark" each element it affects and then check for that mark before applying new event handlers. That way it will only affect newly-loaded code. (It would be more efficient to narrow down the search, however; the expression $('.drag') may have to look through every DOM element on the page, so it would be preferable to use something more precise anyway.)
For one, all the $(this) should be changed to use a variable.
var me = $(this);
me.XXX
$(this) is a method call and its unnessesary to call it over and over again on the same object.
This needs to be done on a per block basis as this will be differet objects in every block ;)
Lookup operations like $(this) are pretty expensive. You'd better store and address object references instead; it helped me a lot in similar circumstances.
It won't make it that much faster, but this will speed it up a few milliseconds:
You should reuse a jquery instance instead of generating a new one (this costs some time).
Example: instead of
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
use
var this_parent = $(this).parent();
this_parent.css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
this_parent.css('color', 'white');
One thing that can significantly optimize the above code is replacing the in_array function and the openedFolders array a JS object that functions as a dictionary and is much more efficient.
Decleration:
openedFolders={};
Add a new folder to the opened folders object:
openedFolders[folderName]=valueRelatedToTheFolderIfYouHaveOneOrWhatEver; // :)
Search for an opened folder:
if(openedFolders.hasOwnProperty(folderName)){/*folderName is open*/}