Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, 16 June 2012

Leting your vital javascript functions to do their job when the content changes

Hi Fellow Programmers

In this post I will show you one way to let your pages work as intended even if they are manipulated dynamically.

The problem: When the content of the page changes dynamically, those items are not listened by those javascript functions which were initialized at the time when the page loaded.

At the very first steps every programmer reinitializes only those handlers which are needed by the dynamically reloaded partial. This has some disadvantages. One of them is that if the initialization changes then it is very painful to track back the partials where the initialization need to be changed. Plus, the whole thing need a babysitting process...

I don't want that...

What I want is a structured way, in which is agile and robust enough to handle these issues... :)

Let me show you by code:
window.problemOrNot = { 
  vital_functions: [
    ->
      $(".cancel").click ->
        $('.cancelable_remove').remove()
        $('.cancelable_show').show()

  ]
  run_vital_functions: ->
    $.each problemOrNot.vital_functions, ->
      @()
}

jQuery ->
  problemOrNot.run_vital_functions()
And then in your partial, which obviously modifies your dom:
$('.comments').append("
  • <%=j render :partial => 'form' %>
  • "); ... ... ... $('#comment_operations').hide(); problemOrNot.run_vital_functions();
    That's it... The first code was in cofee script, and the partial was a rails .js.erb partial. :) Enjoy

    Wednesday, 26 January 2011

    The missing event when the mouse stays in a place

    Hello everybody,

    I just released a jquery plugin which detects if the mouse stays in a place for more than the specified period of millisecs.
    I was missing this functionality and I also needed more than twice and :) I needed also in the past so finally I decided to extract as a reusable plugin.

    You can download it from here:
    or here:

    It is easy to use as any other jquery thing.

    Enjoy :)

    Sunday, 17 October 2010

    Unobtrusive In PlaceEditor for Rails3

    Hello everyone,

    It's been one and half month since Rails3 came out and it evolvolved a lot if we compare it to Rails2. This direction of evolution makes me happy.
    The topic I want to write about is related to the Rails3 way of unobtrusive Javascript. To be more specific I want to show you a way how to make the scriptaculous' in place editor unobtrusive.
    The idea: wouldn't it be nice if by adding some extra attributes to some html tag the displayed entity fields would become spontaneously editable?


    <p id="<%= project.id %>_project_content"
    data-in-place-editable="true"
    data-entity="project"
    data-field="content"
    ><%= project.content %></p>

    I think it definitely would.

    So let's start with it.

    Let's suppose that we have a restfull resource called project and we want an in place editor in our view which is bind to the update method of our ProjectsController.
    First thing you need to do is to check out the http://github.com/orbanbotond/Fast-In-Place-Editor. into your public/javascript directory of your project.
    This file contains the generic repetitive mundane line's of code which would otherwise been repeated field by field in your view.

    In your layout file you need to include this javascript:

    <%= javascript_include_tag "myextensions/fast_in_place_editor.js" %>


    In your view add some extra attributes to the tag which displays your entity's fields. Let's say this is how you were displaying the content of a project:

    <p id="<%= project.id %>_project_content"><%= project.content %></p>

    In order to make the content in place editable do this:

    <p id="<%= project.id %>_project_content"
    data-in-place-editable="true"
    data-entity="project"
    data-field="content"
    data-url="<%= project_path(project, :authenticity_token => form_authenticity_token) %>"
    data-cols="60"
    data-rows="6"
    ><%= project.content %></p>


    And that's all you need to do.
    Enjoy :)



    Wednesday, 4 November 2009

    A quick fix for swfir and prototype incompatibility



    Hi,

    Some of you might know about a small and smart library called swfir. This library intends to extend some of the limitations of classic html images. It can rotate the images and it can draw some fancy borders and fancy shadows around the borders and so on. I like the library despite the fact that it's not perfect. It's not compatible with prototype. :(

    Here is a small patch that I posted to the authors and hopefully a new release will come out which will support prototype :)

    Untill then you can use the patch from here:

    @@ -569,7 +569,11 @@
    Flash Vars
    */
    var varString = "";
    - for(va
    r key in this.params){ varString += ("&"+key+'='+ this.params[key]); }
    + for(var key in this.params){
    + if("function" != typeof(this.params[key])){
    + varString += ("&"+key+'='+ this.params[key]);
    + }
    + }
    Rendering before:

    Rendering after:


    Wednesday, 13 February 2008

    Upload progress bar by streaming JSON

    Have you ever dealt with the problem of making an upload progress bar?
    If you did, then it's time to continue reading.

    I wanted to make one using javascript.
    Basically, there are two alternatives:
    • The simpler one is to make periodic ajax requests to a url. That url must return the received_size/ total_size pair. All you need to do is to update your progress bar in the browser. This solution works in all those browsers which support AJAX. The disadvantage is that the browser will usually receive the (received_size/totoal_size) data pair delayed. So the progress bar won't show you the real progress.
    • The second option would be to use streaming. Instead of periodically polling the server, we should make one single request, and the server would stream the receive_size/total_pair data back to the browser.
    I like this streaming alternative much more because it gives you a better UI experience.
    Let me give you some hints on the streaming alternative.
    • The simplest and the secure way is to stream sequences of '<script type='text/javascript'>updateProgressBar(total, received)</script>' back to the browser. The returned javascript will be automatically executed in IE 6.0, Firefox, Safari and Opera. You can find a solution for this at Ry Dahl's article. However it works in a lot of browsers it's not the most elegant solution because you need to hardcode updateProgressBar in the server configuration file.
    • A little bit more elegant solution is to stream JSON expression like {"total_size": 10, "received_size": 0}; {"total_size": 10, "received_size": 1}; {"total_size": 10, "received_size": 2}; ...
    If you are streaming JSON expressions you need to write a javascript function which updates the progress bar according to the last JSON slice. You can do this using this javascript utility. This script periodically checks the received content and calls your updateProgressBar function passing the last received JSON slice to it. Unfortunately this script doesn't works with the latest prototype library.

    The shortest and the most elegant alternative is to use the "onInteractive" AJAX callback function. By using this callback we don't need to periodically check the response. It is called every time when new data arrives to the browser.
    Look at this beautifull code:
    new Ajax.Request('/upload/progress', {
    pos :0,
    onInteractive: function(obj) {
    var slice = obj['responseText'].slice(this.pos)
    var jsonFormat = slice.substring(0,slice.length - 2);
    var json = jsonFormat.evalJSON();
    updataProgressBar(json.totalSize, json.receivedSize);
    this.pos = obj['responseText'].length + 1;
    },
    });

    Unfortunately this callback doesn't work in Opera neither in IE.
    And I didn't find any w3 recommendation for enforcing the browsers to implement it. :(

    Let me summarize the opportunities and how are they supported on different browsers:

    Opera latestFirefox 2.0.0.2WebkitSafariIE 6IE 7
    Periodic Ajax callsokokokokokok
    Streaming <script> tagsokokokokokok
    Streaming JSON, using Ry's javascriptokokokoknot workingnot working
    Streaming JSON, using onInteractionnot workingokoknot workingnot workingnot working

    So I need to keep up hacking till AJAX standard is born and implemented... :))