Posts Tagged ‘javascript’

Accessing Links in Nested TD Cells with Prototype

Posted 17 Nov 2009 — by admin
Category javascript

There must be a better way to do the following with PrototypeJS. I want to loop over nested links inside of table td cells and apply a class to the row that the link is in when the link is clicked. If a user clicks on another link the class will be removed and applied to the current table row.

The code below works but I think it seems hackish. Any thoughts on improving this code?

Here is the link to the pastie http://pastie.org/703316

# This is the table with haml markup
%table
  %tr
    %td
       info
    %td
      = link_to "be clicked", remote_request_goes_here_path

And the Js

	$$("td.filter_link > a").each(function(element){
		Event.observe(element, "click", function(event){
			$$("td.filter_link").each(function(el){
				if(el != this){
					el.up().removeClassName("turnwhite");
				}
			});
                       // apply the turnwhite class to the table row
			this.up().up().addClassName("turnwhite");
		});
	});

TinyMCE Rich Text Editor: HELLO EDITOR Plugin Tutorial and Example

Posted 06 Nov 2009 — by admin
Category Wordpress

I wanted to create a button for the TinyMCE Rich Text Editor for Wordpress. It was tough to find good docs on the subject. There are a couple of useful posts out there but in general I found them lacking.

http://codex.wordpress.org/TinyMCE_Custom_Buttons#Creating_an_MCE_Editor_Plugin

The above resource has a good section on the PHP code needed to write your own callbacks but there is no mention of the JavaScript required to create a button and interact with it. Links are available for more reading but why not also post a code sample to get up and running?

Anyway, I made a simple plugin after hobbling a bunch of resources together to get a button in the text editor that when clicked triggers an alert to the window. The code isn’t fancy but it might provide a starting off point for a larger project or be useful as a resource for some of the basic ideas involved. I read through a couple of the sample plugins included with Wordpress along with the Viper Video Quicktags Plugin, which makes extensive use of the feature. However, they were too complex for a quick, basic understanding.

This plugin doesn’t do a lot. I’ll probably flesh it out a bit more when I have a clearer understanding of how it all works. For now here are some code samples and at the bottom of this post there is a link to the .zip file for the plugin which you can install on your own site.

In wp-content/plugins/hello_editor/index.php

<?php
/*
Plugin Name: Hello Editor
Plugin URI: http://seanbehan.com/wordpress/tinymce-rich-text-editor-hello-editor-plugin-tutorial-and-example/
Description: A simple plugin showing how to add a button to the rich text editor in Wordpress.
The plugin doesn't do anything except place a button and respond to onclick event, with "Hello Editor".
Most of the editor plugins available are too 'functional' to quickly read and see how to do the
basics. This plugin doesn't 'do' anything, rather it makes it simple to read what is going on.
Version: 0.1
Author: Sean Behan
Author URI: http://seanbehan.com
*/

define( "HELLO_EDITOR_PLUGIN_DIR", "hello_editor" );
define( "HELLO_EDITOR_PLUGIN_URL", "/wp-content/plugins/" . HELLO_EDITOR_PLUGIN_DIR );

// Register the external pllugin from the .js file
function hello_editor_register_external_plugin($plugin_array) {
  $plugin_array['HELLO_EDITOR'] = HELLO_EDITOR_PLUGIN_URL . '/editor_plugin.js';
  return $plugin_array;
}

// Add the button to the array ***NOTE*** The name here "HELLO_EDITOR" must
//match the name in the editor plugin file for the addButton(name_of_button) function!
function hello_editor_register_button($buttons) {
  array_push( $buttons, "|", "HELLO_EDITOR" );
  return $buttons;
}

// Filters which will call our functions
function hello_editor_init(){
  add_filter("mce_external_plugins", "hello_editor_register_external_plugin");
  add_filter('mce_buttons', 'hello_editor_register_button');
}

// When the editor is initialized
add_action('init', 'hello_editor_init');

In wp-content/plugins/hello_editor/editor_plugin.js

(function() {
  //Init the plugin
  tinymce.create('tinymce.plugins.HELLO_EDITOR', {
    init : function( ed, url ) {
    //addButton name needs to match $plugin_array['HELLO_EDITOR'] in add_filter function
    ed.addButton('HELLO_EDITOR', {
      title : 'Hello Editor',
      image : url + "/buttons/hello.png",
      onclick : function(){
        alert("HELLO EDITOR!");
      }
    });
  },
  //Info about the plugin
  getInfo : function() {
    return {
      longname : "Sean Behan's Sample Hello Editor Plugin",
      author : 'Sean Behan',
      authorurl : 'http://www.seanbehan.com/',
      infourl : 'http://seanbehan.com/wordpress/tinymce-rich-text-editor-hello-editor-plugin-tutorial-and-example/',
      version : "0.1"
    };
  }
});
tinymce.PluginManager.add('HELLO_EDITOR', tinymce.plugins.HELLO_EDITOR);
})();

You’ll also need a directory called buttons inside the hello_editor plugin directory with a hello.png file which will be displayed. Without it you’ll just get a blank button. You can rename this but remember to change the name in the editor_plugin.js file as well.

You can download the sample plugin here http://seanbehan.com/wp-content/uploads/2009/11/hello_editor.zip

Double Click Event Using Prototype Javascript Framework

Posted 11 Aug 2009 — by admin
Category Programming

Super simple to get double click “desktop” like functionality out of Prototype! For some reason, googling it doesn’t yield many useful results. http://www.google.com/#hl=en&q=double+click+in+prototype+javascript&aq=f&oq=&aqi=&fp=peEfEjG9pWY :(

Anyway, here is the code

	document.observe('dblclick', function(){
		alert("Hello World");
	});

Using Prototype to Access Form Data

Posted 26 Mar 2009 — by admin
Category Programming

Prototype has a powerful API for accessing and manipulating the Document Object Model, A.K.A the DOM. The following code will let you interact with a simple web form.

Suppose we have a form that contains hidden/or locked inputs and they need to be updated dynamically. If the user changes a select field or if a checkbox is de/selected, other values in the form need updating. This could be required when products have options and associated price points. If you want to offer the user the option to switch options without refreshing or navigation this is a simple and effective approach.

… Sample form…

<input type="hidden" name="option_plan_id" id="option_plan_id" value="1"><br/>
<input type="hidden" name="amount" value="150" id="amount">

<select name="select-plan" id="select-plan">
<option value="1, 150">
USD 150 - 1 person
</option>
<option value="2, 200">
USD 200 - 2 people
</option>
</select>

In this example I want to update the values on the amount and option_plan_id input fields. The first thing I need to make sure of is that the page has fully loaded. I’ll make sure that my code executes in this context by placing it inside the document.observe method. I’ll then set up an observer on my select field and if it changes, make assignments. Now, in this example, I just saved the plan id and amount information as a string. In my javascript code I split apart the string and then make the assignments. There are other, probably better, ways of doing this. For instance you could store serialized data/json, and then work with it inside your event. This seems simple enough, however, you’ll have to pay attention in the future, if your storage format changes! Here is the sample Prototype javascript code

<script type="text/javascript" charset="utf-8">
document.observe("dom:loaded", function(){ //when dom is fully loaded do -
//update fields when option is selected
Event.observe('select-plan', 'change', function(event){
var data = this.getValue();
var plan = data.split(",").first(); //breaks apart by comma
var amount = data.split(",").last();
$('plan_option_id').setAttribute('value', plan);
$('amount').setAttribute('value', amount);
});
});
</script>

Thats it for now!

Parse for Links with Prototype JS

Posted 25 Mar 2009 — by admin
Category Programming

Parsing for links with the Prototype javascript library is easy. Here is the pattern for finding links

/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/

And to implement it you can loop through your containers that might contain links

document.observe("dom:loaded", function(){
var posts = $$("div#posts");
for(var i = 0; i < posts.length; i++){
var link_regex = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
var parsed_string = posts[i].innerHTML.gsub(link_regex, '<a href="#{0}"
target="_blank">#{0}</a>');
posts[i].innerHTML = parsed_string;
}
});