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

Thursday, December 27, 2012

Assign class or function to Dom element on the fly

Hello Guys,
        Want to assign the class to dom element on the fly? then simply use javascript function which listed below.

demo.html

Lets assume we have anchor tag on it's click we have to apply css class.

<a id="anchor" href="" target='_blank' class='active' onclick="javascript:open_url(this.id, 'google.com');"> Open this link in new window or tab </a>

// javascript  function
<script type='javascript'>
  function open_url(id, url){
   // verify dom has 'active' class or not
   if ($('#' + id).hasClass('active')) {
     if(url != ''){
    // it's open url in new window
     window.open(url);
   }
  }
}
</script>

Saturday, August 4, 2012

Replace double space with   in javascript

Hello Guys,
        Last time when i was playing with double spaces.. found the interesting thing. When passing the double space string from javascript (view) to controller , it converts the valid space to non-breaking space.

Lets see the eg.

View: index.rhtml

a = "This  is the pen"
a.gsub("  ", "&nbsp;&nsbsp;")

<script language='javascript/text'>
 
  /* Now assign the value to input element by */
  $('txtid').value = <%= a %>;

 // Get value back encodeURIComponent($('txtid'))

</script>
 
at controller

def any_method
   # replace '\xC2\xA0' or '&nbsp;' with ' '
   params[:a].gsub("\xC2\xA0", " ").gsub("&nbsp;", " ")
end

Hope above article is helpful to you guys.

Wednesday, June 20, 2012

Ajax request via javascript

Hello Rubies,
      Have you tried AJAX request via javascript? Lets see the eg.

<script type="text/javascript">

  // Ajax without update parameter:
  function ajax_request(id){
    window._token = '<%= form_authenticity_token %>';
    var url = '/controller/action';
    var pars = 'id=' + id + '&authenticity_token=' + window._token;
    var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onFailure: showFailure(), onSuccess: showSuccess() });
  }

  // Ajax with update parameter:
  function ajax_update_request(id){
    window._token = '<%= form_authenticity_token %>';
    var url = '/controller/action';
    var pars = 'id=' + id + '&authenticity_token=' + window._token;
    var myAjax = new Ajax.Updater('update_div_id', url, {method: 'get', parameters: pars, onFailure: showFailure(), onSuccess: showSuccess()});
  }

  function showSuccess(){
  }

  function showFailure(){
  }

</script>

Wednesday, January 4, 2012

Undefined method Object.keys


Hello Guys,
        Object.keys is depreciated and it does not support in some of the browsers like IE, FF 3.x. So we have to add the javascript object.keys method to overcome this problem.

Object.keys = function(obj) {
   if (typeof obj != "object" && typeof obj != "function" || obj == null) {
     throw TypeError("Object.keys called on non-object");
   } 
   var keys = [];
   for (var p in obj) obj.hasOwnProperty(p) && keys.push(p);
   return keys;
}

Now see we resolve the javascript error 'Undefined method Object.keys'.

Thursday, October 13, 2011

Escape or Encode the character using javascript or ruby

Guys,
          When we are storing the data in the database using any encoding method like UTF-8 and retrieve data in javascript it gives us in output in decode and unescape format.

To solve above issue using javascript or ruby
Javascript functions:
escape(String) - unescape(String)
encodeURI(String) - decodeURI(String)
encodeURIComponent(String) - decodeURIComponent(String)

Ruby methods:
CGI.escape(String) - CGI.unescape(String) or CGI.unescapeHTML(String)
URI.escape(String) - URI.unescape(String)

Online tool for escape/unescape, encode/decode the character.
http://www.the-art-of-web.com/javascript/escape/

Friday, September 2, 2011

Ajax based pagination

Hello Guys,
          There are different plugin and gem available for pagination. I would like to prefer will_paginate gem for pagination in rails.

First of all we have to add mislav-will_paginate gem via
sudo gem install mislav-will_paginate
 
or specify in your environment.rb

config.gem "mislav-will_paginate", :lib => "will_paginate", :source => "http://gems.github.com"

in your pagination.js add the javascript code to support ajax based pagination

document.observe("dom:loaded", function() {
  var container = $(document.body)

  if (container) {
    # uncomment below code to load spinner
    //var img = new Image
    //img.src = '/images/spinner.jpeg'  
    function createSpinner() {
      //return new Element('img', { src: img.src, 'class': 'spinner' })
    }

    container.observe('click', function(e) {
      var el = e.element()
      if (el.match('.pagination.ajax a')) {
          el.up('.pagination.ajax').insert(createSpinner())
//      if (el.match('.pagination a')) {
//        el.up('.pagination').insert(createSpinner())
        new Ajax.Request(el.href, { method: 'get' })
        e.stop()
      }
    })
  }
})

Now you have to include pagination.js in your view through
<%= javascript_include_tag 'pagination' %>

Lets we implement pagination on index method of users controller.

users_controller.rb

def index
  @users = User.all.paginate(:per_page => 20,:page => params[:page])
  respond_to do |format|
    format.html
    format.js {
      render :update do |page|       
        page.replace_html 'user_list', :partial => 'user_list', :locals => {:users => @users}
      end
    }
    end
end

Now move towards the views. here we have 3 views which listed below.

i) index.html.erb
   <h1> Listing Users </h1>
   <table>
     <tr>
       <th> Name </th>
       <th> Surname </th>
     </tr>
     <tbody id='user_list'>
        <%= render :partial =>'user_list', :locals => {:users => @users} %>
     </tbody>
   </table>

ii) _user_list.html.erb

  <% users.each do |user| %>
    <tr>
      <td> <%= user.name %> </td>
      <td> <%= user.surname %> </td>
    </tr>
  <% end %>
  <tr>
   <td colspan="2"> 
      <%= will_paginate users, :class => 'pagination ajax', :id=>"flickr_pagination"%>
   </td>
  </tr>

iii) index.js.erb
      $("#user_list").html("<%= escape_javascript(render :partial => "user_list") %>");

This is the file which actually play with ajax during pagination.

Now add pagination.css in style sheet for better formatting

#flickr_pagination {
  text-align: center;
  padding: 0.3em 0.3em 0.3em 0.3em;
  clear:both;
  margin:5px 0px 5px 0px;
  }
#flickr_pagination * {
  font: 10pt Arial,Helvetica,Geneva,sans-serif;
  } 
#flickr_pagination a, #flickr_pagination span {
  padding: 0.2em 0.5em; 
  }
#flickr_pagination span.disabled {
  color: #AAA
AAA;
  }
#flickr_pagination span.current {
  font-weight: bold;
  color: #898989; 
  }
#flickr_pagination a {
  border: 1px solid #DDDDDD;
  color: #0072BC;
  text-decoration: none; 
  }
#flickr_pagination a:hover, #flickr_pagination a:focus {
  border-color: #DDDDDD;
  background: #898989;
  color: #FFFFFF; 
  }
#flickr_pagination .page_info {
  color: #aaaaaa;
  padding: 0.8em 0em 0em 0em; 
  }
#flickr_pagination .prev_page, #flickr_pagination .next_page {
  border-width: 1px; 
  }
#flickr_pagination .prev_page {
  margin: 0em 1em 0em 0em; 
  }
#flickr_pagination .next_page {
  margin: 0em 0em 0em 1em; 
  }

you have to include pagination.css in your view through
<%= stylesheet_link_tag 'pagination' %>

Finally we done with ajax pagination. If you want different styles for pagination then just replace the style sheet. http://woork.blogspot.com/2008/03/perfect-pagination-style-using-css.html

Hope this post will help you to implement ajax pagination in rails.