Thinking on hiring me?

Please read

Fernando Guillén

a Freelance Web Developer

cabecera decorativa

software development as an artistic expression

Archive for the ‘javascript’ Category

Jueves, Julio 9th, 2009

jQuery: deleting the last word from textarea’s cursor

Following with the completor suggestor I was playing, I had the need to delete the last word from cursor before the completor writes the suggestion selected.

Thanks to the previous function textarea.lastWord() it was  very easy:

jQuery.fn.deleteLastWord = function() {
  this.each(function(){
    if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
 
      var lastWord = $(this).lastWord();
      startPos = startPos - lastWord.length;
 
      this.value =
          this.value.substring(0, startPos) +
          this.value.substring(endPos, this.value.length);
      this.focus();
      this.selectionStart = startPos;
      this.selectionEnd = startPos;
      this.scrollTop = scrollTop;
    } else {
      alert("deleteLastWord not supported on this navigator");
    }
  });
};

Example of use:

$('#my_textarea').deleteLastWord();

Don’t copy and paste from here, WP does weird stuff with code, download from here: http://gist.github.com/143822

This script is almost not tested, it works for me on FireFox 3.0.11 and Safari 4.0.1, so use it under your own responsability.

Jueves, Julio 9th, 2009

jQuery: returning the last word from textarea’s cursor

I was enjoying trying to develop a kind of completor suggestor on a textarea, I wanted it to jump when the tab key was pressed, that what easy with capturing the keydown event and the help of event.preventDefault.

But the thing what wasn’t such easy was the capturing the last word on the textarea from the cursor.

But with the help of the code of the insertAtCaret function I was abble to obtain it:

jQuery.fn.lastWord = function() {
  var buffer = '';
 
  this.each(function(){
    if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
 
      var index = 0;
      var new_char = '';
 
      do{
        index += 1;
        buffer = new_char + buffer;
        new_char = this.value.substr(startPos - index, 1);
      } while( new_char.search( /^(\w|\.)$/|> ) != -1 )
 
    } else {
      alert("lastWord not supported on this navigator");
    }
  });
 
  return buffer;
};

Example of use:

alert( "last word from cursor: " + $('#my_textarea').lastWord() );

Don’t copy and paste from here, WP does weird stuff with code, download from here: http://gist.github.com/143808

This script is almost not tested, it works for me on FireFox 3.0.11 and Safari 4.0.1, so use it under your own responsability.

Lunes, Agosto 11th, 2008

Ruby, script generador de script javascript para precarga de imágenes en tu html

El truco más sencillo para precargar las imágenes de tu web y así no ver el horrible efecto de mouse-over hueco es hacer un script javascript como este:

img1 = new Image();
img1.src="imagen.jpg";

Esto invocará la imagen y el navegador, sino es muy tonto, la dejará en la caché para cuando verdaderamente la necesite.

Bueno, pues es lo que quiero hacer para una web que tiene un montón de background-image definidos en su css.

Para ello me he hecho un script en ruby que me busca todas las imágenes en todos los css y me genera un script de javascript con todo el rollito de los preload.

class Preloator
  def self.generate_script( css_directory )
    # take all .css on directory
    css_file_names = []
    Dir.foreach( css_directory ) do |file|
      if file =~ /.*\.css$/
        css_file_names << css_directory + '/' + file
      end
    end
 
    # take all the images by looking at 'url'
    image_names = []
    css_file_names.each do |file_name|
      self.grep( 'url', file_name ).each do |line|
        image_names << line.scan( /.*\((.*)\)/ ).flatten.first
      end
    end
 
    # generate the script
    script = "<script>\n"
    image_names.each_with_index do |image_name, index|
      script += "    img#{index} = new Image();\n"
      script += "    img#{index}.src = \"#{image_name}\";\n"
    end
    script += "</script>"
  end
 
  def self.grep( pattern, filename )
    matches = []
    regexp = Regexp.new( pattern )
    File.open(filename) do |file|
      file.each do |line|
        matches << "#{filename} #{file.lineno.to_s}: #{line}" if regexp.match(line)
      end
    end
    matches
  end
end
 
puts Preloator.generate_script( ARGV[0] )

Esto genera una salida como esta:

$ ruby etc/preloator.rb public/stylesheets/
<script>
img0 = new Image();
img0.src="/imgs/fondo.jpg";
img1 = new Image();
img1.src="/imgs/fondo_carpeta.png";
img2 = new Image();
img2.src="/imgs/blog_sombra_abajo.png";
img3 = new Image();
</script>;

Seguramente quieras mejorarlo un poquito: meterlo en un .js o invocarlo cuando el document.load.

El script ahorra trabajo si, como en mi caso, tienes más de 20 imágenes en el css.. y escribir el javascript a mano sería un coñazo.

a Freelance Web Developer is proudly powered by WordPress
Entries (RSS) and Comments (RSS).

Creative Commons License
Fernando Guillen's blog by Fernando Guillen is licensed under a Creative Commons Attribution-NoDerivs 3.0 Unported License.