You are currently browsing the tag archive for the ‘Javascript’ tag.

Works for text input, checkboxes, radio, select, textarea

function isFilled(e){
  var type = e.getAttribute('type');
  if(type == 'radio' || type == 'checkbox'){
    return e.checked
  } else {
    return !e.value.empty()
  }
}

function anyFieldFilledIn(e){
  return e.select('input, select, textarea').map(function(e){return isFilled(e)}).any()
}

I recently set out to find a good slideshow for our homepage, but most of them are monsters, with 20kb code, no thanks…
The simples/best solution i found was the s3Slider somewhat simple and looks good.

But after it started behaving silly (sliding to fast/slow, hanging on mouseover) I decided to fix it and discovered a pile of spaghetti. So here is my s3_slider rewrite download that is smaller(now ~1kb) / simpler / maintainable and more easy to setup! Demo of the new version

Load JS last, or it will halt the browser while loading… AMEN!

You may protest:
But i use some inline javascript and nothing will work, when jQuery / Prototype / Mootolls / … is not loaded already!!

Version 1: content_for :js

#in your body: (HAML example, works for ERB too...)
%h1 My great title
- content_for :js do
  :javascript
    $(function(){
      $('h1').html('inline js rocks!')
    });

#in you footer
  =js_tag 'jquery', 'application', 'whatever'
  yield :js #this will output all content_for blocks...

Instantly better load times, and no need to abandon inline js!!

Version 2: Caching !?
When action/fragment-caching, this can get problematic, since the content_for will not be call, and hence the js will be missing.
This can be fixed by introducing a ‘later’ method, which gets filled with everything that should be done once your js framework is loaded.

#in your views
later(function(){
  $('#xxx').do_something();
})

#in you footer
later(); //call all those methods that have been stacked...

#in your head
later = function(){
  var stack = [], i_ran=0;
  return function(execute_later){
   if(typeof(execute_later)=='undefined'){
     i_ran=1;
     for(var i=0;i<stack.length;i++)stack[i].call();//execute them all
   } else {
     if(i_ran)execute_later.call()//page is loaded already, just execute
     else stack.push(execute_later)//page not finished, store
   }
 };
}()

So far we parsed our feeds with the acts_as_feed Rails plugin but as long as you only want to show them to users, there is an easier alternative: Googles JS Feed API!

Result

rss feed through google rss api

rss feed through google rss api

(The Example uses jQuery)
Example

<script type="text/javascript" src='http://jqueryjs.googlecode.com/files/jquery-1.3.1.js'></script>
<script type="text/javascript" src='http://www.google.com/jsapi?key=YOUR_API_KEY'></script><script>
google.load("feeds", "1");
$(function(){
  var feed = new google.feeds.Feed("http://rathershort.weblo.gg/rss.xml");
  feed.load(function(result) {
    if (result.error)return;
    $feed = $('#feed_entries');
    for (var i = 0; i < 3; i++) {
      var entry = result.feed.entries[i];
      $feed.append(
        '<div class="home_container_item">'+
          '<h3><a href="'+entry.link+'">'+entry.title.truncate(25)+'</a></h3>'+
          '<div class="small_gray">'+entry.publishedDate.toDate().formatted()+'</div>'+
          '<div>'+entry.contentSnippet.truncate(60)+'</div>'+
          '<br>'+
        '</div>'
        );
      }
    });
  });

//DATE
Date.shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
Date.prototype.formatted = function(){
  return this.getDate()+' '+Date.shortMonths[this.getMonth()]+' '+this.getFullYear();
};

//STRING
String.prototype.toDate = function(){
  var d = new Date();
  d.setTime(Date.parse(this));
  return d;
};

String.prototype.truncate = function(to_length){
  if(to_length >= this.length)return this;
  return this.substring(0, to_length-3)+'...';
};
</script>

Auto complete solution, with customizable results (return just the word or word+id…) and no framework dependency, just use a plain text_field + class=> autocomplete and every autocomplete libary you like (included: jQuery).

autocomplete

# Controller
class UserController < ApplicationController
  autocomplete_for :user, :name
end

#Customized....
autocomplete_for :user, :name do |items,method|
  render :text => items.map{|item| "#{item.send(method)} -- #{item.id}"}.join("\n")
end

# View
<%= f.text_field :auto_user_name, :class => 'autocomplete', 'autocomplete_url'=>autocomplete_for_user_name_users_path %>

# Routes
map.resources :users, :collection => { :autocomplete_for_user_name => :get}

#JS
#any library you like
#(includes examples for jquery jquery.js + jquery.autocomplete.js + jquery.autocomplete.css )
jQuery(function($){//on document ready
  //autocomplete
  $('input.autocomplete').each(function(){
    var input = $(this);
    input.autocomplete(input.attr('autocomplete_url'));
  });
});

#Model(input/output association)
class User
  find_by_autocomplete('name')
end
class Post
  autocomplete_for('user','name') # auto_user_name= + auto_user_name
end
.

Not as thought free as the default version, but gives you a lot more control.

script/plugin install git://github.com/grosser/simple_auto_complete.git
README

Follow

Get every new post delivered to your Inbox.

Join 63 other followers