1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

jQuery named function - run every time

Discussion in 'jQuery' started by PoPSiCLe, Oct 10, 2013.

  1. #1
    Hey. I have a very simple jQuery function for displaying a message box when data arrives via ajax-calls. The code for the function is as follows:

    
    function showUpdateInfo(data,infotype) {
         var setClass = infotype;
         $("#updateinfo").css({'display':'block'}).addClass(setClass).text(data).fadeOut(3500);
         return false;
       };
    
    Code (markup):
    My problem is that this function works, but only if the fadeOut is done - ie, if a user clicks on stuff before the fadeOut is done, a new messagebox with new content doesn't appear - and right now my brain can't seem to figure out what I'm doing wrong. I tried doing an $.each(), but that didn't seem to affect it.

    Anybody able to provide some tips on how to achieve this?
     
    Solved! View solution.
    PoPSiCLe, Oct 10, 2013 IP
  2. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #2
    Hey PoPSiCLe,

    Are you adding links into the data that is added dynamically? If so you need to use the "on" method to be able to detect clicks from content that wasn't there when the page was loaded originally.

    API: http://api.jquery.com/on/

    Let me know if that was the problem and if you need any help with using it. If this wasn't the solution show me all of your source code and I will have a look.
     
    HuggyStudios, Oct 11, 2013 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Nope. The page (unfortunately behind a login) is a timesheet overview, with a list of days/weeks/locations, and checkboxes for each - when a user clicks the checkbox, it displays a div with content saying either "User has been added to this shift" or "User has been removed from this shift" - that content is being retrieved via the ajax-function for sending info to the background php-file. The content is basically just what gets sent back by data in the ajax-function.
     
    PoPSiCLe, Oct 13, 2013 IP
  4. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #4
    Hey,

    Can I see the source code?
     
    HuggyStudios, Oct 13, 2013 IP
  5. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #5
    Here's the js for the whole thing, apart from the function mentioned above:
    
    $(function() {
    
         var preDraggedName = "";
    
         // this makes the TDs with usernames draggable
      $(".draggable").draggable({ snap: true, snap : 'td.droppable',
         drag: function( event, ui) {
           var getDate = $(this).parents('td').prevAll('.datecell').text().replace(/ /g,'');         
         var tempName = $(this).find('input').attr('name');
         var splitName = tempName.split('_');
             if (typeof splitName[3] === 'undefined') {
                 preDraggedName = tempName+'_'+getDate;
               } else {
                 preDraggedName = tempName;
               }
           }
         });
    
      // this makes the TDs droppable (provides a place to drop the draggable items)
      $(".droppable").droppable({ accept: ".draggable", revert: true,
         drop: function( event, ui) {
         var dropped = ui.draggable;
         var droppedOn = $(this);
         var droppedContent = ui.draggable.text();
         // console.log(droppedContent);
         var signups = droppedOn.find('.nosignups');
         var nosignups = '<span class="nosignups">Ingen har satt seg opp på dette skiftet</span>';
         var existingContent = [];
         droppedOn.find(".draggable").each(function() {
           existingContent.push($(this).text());
    
         });   
               // console.log(existingContent);
         if ($.inArray(droppedContent,existingContent) !== -1) {
           ui.draggable.draggable('option','revert',true);
           showUpdateInfo("Brukeren er allerede satt opp på dette skiftet",'error');
         }
         else {
           var draggedParent = ui.draggable.parent("td");
           $(dropped).detach().css({top: 0, left: 0}).appendTo(droppedOn);
           var oldname = $(dropped).find('input').attr('name').split('_');
           var newshift = $(dropped).parent('td').attr('class').split(' ');
           var newshift = newshift[0].split('_');
           var newname = "";
           for (var i = 0; i < oldname.length; i++ ) {
               newvalue = oldname[i];
             if (i == 2) {
               newvalue = newshift[1];
             }
             newname += newvalue+'_';
           }
           var newname = newname.substr(0, newname.length -1);
           $(dropped).find('input').attr('name',newname);
             $(signups).remove();
             var ifEmpty = draggedParent.find("span");
             if ($(ifEmpty).length == 0) {
               $(draggedParent).html(nosignups);
             };
         }
      }
         });
    
         
         $("#coordinate_table input[type=checkbox]").click(function() {
             var coordinate = 'coordinate';
             var currentCheckBoxName = $(this).attr('name');
             var explodedName = currentCheckBoxName.split('_');
             var getDate = $(this).parents('td').prevAll('.datecell').text().replace(/ /g,'');         
             var isShiftleader = $(this).parent('span').hasClass('shiftleader');
             var userID = $(this).val();
             // var selectedDate = $(this).parents('tr').find('.datecell').text();
             var selectedShift = $(this).parents('td').attr('class').split(' ');
             var params = { };
             params['predraggedname'] = preDraggedName;
             params[coordinate] = 'yes';
             params['studentid'] = userID;
             if ($(this).is(':checked')) {
               if (typeof explodedName[3] === 'undefined') {
                 var currentCheckbox = currentCheckBoxName + '_' + getDate;
               } else {
                 var currentCheckbox = currentCheckBoxName;
               }
                 params[currentCheckbox] = "on";
                 params['workdate'] = currentCheckbox;
                 $(this).attr('name',currentCheckbox);
             } else {
                 var currentCheckbox = explodedName[0] + '_' + explodedName[1] + '_' + explodedName[2];
                 // params['unchecked'] = "yes";
                 params[currentCheckBoxName] = "off";
                 params['workdate'] = currentCheckBoxName;
                 $(this).attr('name',currentCheckbox);
             }
           if ($(this).is(':checked')) {
             console.log(params);
             // alert(currentCheckbox + ' ' + isShiftleader + ' ' + userID + ' checked');
           } else {
             console.log(params);
             // alert('unchecked');
           }
           $.post("timesheet/timesheet_register.php",params,function(data) { if (data != "") { //alert(data);
             showUpdateInfo(data,'success');
                 $('input[name="'+ escape(currentCheckbox)+'"]'); } });
         })
         
       });
    // end coordinate-funcionality
    
    Code (markup):
     
    PoPSiCLe, Oct 15, 2013 IP
  6. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #6
    For it to work and not work when the content changes makes me think that it's related to the element not existing. Try this code.
    
    $(function() {
    
         var preDraggedName = "";
    
         // this makes the TDs with usernames draggable
      $(".draggable").draggable({ snap: true, snap : 'td.droppable',
         drag: function( event, ui) {
           var getDate = $(this).parents('td').prevAll('.datecell').text().replace(/ /g,'');        
         var tempName = $(this).find('input').attr('name');
         var splitName = tempName.split('_');
             if (typeof splitName[3] === 'undefined') {
                 preDraggedName = tempName+'_'+getDate;
               } else {
                 preDraggedName = tempName;
               }
           }
         });
    
      // this makes the TDs droppable (provides a place to drop the draggable items)
      $(".droppable").droppable({ accept: ".draggable", revert: true,
         drop: function( event, ui) {
         var dropped = ui.draggable;
         var droppedOn = $(this);
         var droppedContent = ui.draggable.text();
         // console.log(droppedContent);
         var signups = droppedOn.find('.nosignups');
         var nosignups = '<span class="nosignups">Ingen har satt seg opp på dette skiftet</span>';
         var existingContent = [];
         droppedOn.find(".draggable").each(function() {
           existingContent.push($(this).text());
    
         });  
               // console.log(existingContent);
         if ($.inArray(droppedContent,existingContent) !== -1) {
           ui.draggable.draggable('option','revert',true);
           showUpdateInfo("Brukeren er allerede satt opp på dette skiftet",'error');
         }
         else {
           var draggedParent = ui.draggable.parent("td");
           $(dropped).detach().css({top: 0, left: 0}).appendTo(droppedOn);
           var oldname = $(dropped).find('input').attr('name').split('_');
           var newshift = $(dropped).parent('td').attr('class').split(' ');
           var newshift = newshift[0].split('_');
           var newname = "";
           for (var i = 0; i < oldname.length; i++ ) {
               newvalue = oldname[i];
             if (i == 2) {
               newvalue = newshift[1];
             }
             newname += newvalue+'_';
           }
           var newname = newname.substr(0, newname.length -1);
           $(dropped).find('input').attr('name',newname);
             $(signups).remove();
             var ifEmpty = draggedParent.find("span");
             if ($(ifEmpty).length == 0) {
               $(draggedParent).html(nosignups);
             };
         }
      }
         });
    
         
         $(document).on('click', "#coordinate_table input[type=checkbox]", function() {
             var coordinate = 'coordinate';
             var currentCheckBoxName = $(this).attr('name');
             var explodedName = currentCheckBoxName.split('_');
             var getDate = $(this).parents('td').prevAll('.datecell').text().replace(/ /g,'');        
             var isShiftleader = $(this).parent('span').hasClass('shiftleader');
             var userID = $(this).val();
             // var selectedDate = $(this).parents('tr').find('.datecell').text();
             var selectedShift = $(this).parents('td').attr('class').split(' ');
             var params = { };
             params['predraggedname'] = preDraggedName;
             params[coordinate] = 'yes';
             params['studentid'] = userID;
             if ($(this).is(':checked')) {
               if (typeof explodedName[3] === 'undefined') {
                 var currentCheckbox = currentCheckBoxName + '_' + getDate;
               } else {
                 var currentCheckbox = currentCheckBoxName;
               }
                 params[currentCheckbox] = "on";
                 params['workdate'] = currentCheckbox;
                 $(this).attr('name',currentCheckbox);
             } else {
                 var currentCheckbox = explodedName[0] + '_' + explodedName[1] + '_' + explodedName[2];
                 // params['unchecked'] = "yes";
                 params[currentCheckBoxName] = "off";
                 params['workdate'] = currentCheckBoxName;
                 $(this).attr('name',currentCheckbox);
             }
           if ($(this).is(':checked')) {
             console.log(params);
             // alert(currentCheckbox + ' ' + isShiftleader + ' ' + userID + ' checked');
           } else {
             console.log(params);
             // alert('unchecked');
           }
           $.post("timesheet/timesheet_register.php",params,function(data) { if (data != "") { //alert(data);
             showUpdateInfo(data,'success');
                 $('input[name="'+ escape(currentCheckbox)+'"]'); } });
         })
         
       });
    // end coordinate-funcionality
    
    Code (markup):
    If that doesn't fix it, let me know.
     
    HuggyStudios, Oct 15, 2013 IP
  7. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #7
    No difference. The problem is not the element not existing - the element exists as an empty div on the page, and gets called and filled each time an ajax-request is sent. It just doesn't refresh while the fadeOut is in play. Hence, I need a way to end the fadeOut before the timer ends, and display the element anew, with new content.
     
    PoPSiCLe, Oct 15, 2013 IP
  8. chifliiiii

    chifliiiii Active Member

    Messages:
    31
    Likes Received:
    3
    Best Answers:
    3
    Trophy Points:
    55
    #8
    Hi! Would be great if we can see a link and test it. But look at this:
    
    function showUpdateInfo(data,infotype) {
       
        $("#updateinfo").show().addClass(infotype).text(data).fadeOut(3500);
    
      };
    
    Code (markup):
    check the function working on http://jsfiddle.net/Z3Bv6/
     
    chifliiiii, Oct 17, 2013 IP
  9. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #9
    That doesn't work, as far as I can see. The timer you've set is running longer than the fadeOut - hence defeating the purpose. If you set the timer to 500 instead of 4000, it won't update during fadeOut.

    Made a clickable div to show you how it doesn't work - http://jsfiddle.net/Z3Bv6/1/
     
    PoPSiCLe, Oct 17, 2013 IP
  10. chifliiiii

    chifliiiii Active Member

    Messages:
    31
    Likes Received:
    3
    Best Answers:
    3
    Trophy Points:
    55
    #10
    My example was working to me, and the one you send also seems to work to me. Did you tried with other browsers? MAybe you loaded a weird addon in your browser that generates js errors. I´ve seen that a lot
     
    chifliiiii, Oct 17, 2013 IP
  11. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #11
    Uhm - it doesn't work in Firefox or Chrome. What do you define for "working"? Working means it will refresh IF the fadeOut is NOT done, and start the fadeOut again - which it doesn't do at all. If I click the "Click here" while the fadeOut is happening, nothing changes - and I'll have to click it again after the fadeOut is done, to get a new info-box displayed.
     
    PoPSiCLe, Oct 17, 2013 IP
  12. #12
    Ohhh I see, i didn't understand you. So you want to update the result when is fading out. In that case you need to cancel animation first using stop()

    Check my example again http://jsfiddle.net/Z3Bv6/4/
     
    chifliiiii, Oct 17, 2013 IP
    PoPSiCLe likes this.
  13. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #13
    Aha. I knew it was something very small and simple :D Thank you!
     
    PoPSiCLe, Oct 17, 2013 IP