jQuery context menu

Project on Github

code and issues on github: https://github.com/danielecr/jquery-contextual-menu !

Prize

June 2014 jsclasses.org innovation award

Thanks to this prize I got a book from Addy Osmani, design pattern in javascript.

The idea behind context menu

Ok, I admit I do not search to much out there if this is available..

A simple jquery plugin that permit to show context menu

I take inspiration from yahoo library: here is an example

But I want it as jquery plugin and also I want to have option to choose the way it should work, for example I also want to fire context menu on hold down left mouse button for 1 second, or just hover on element.

Also I want that normal click behave correctly on anchor elements that have option menu installed on those, thus click is a click, hold down for 1 second is a context menu fireup.

Ok, I have put it in a plugin, also I have made an example of the use with a small drupal module that use the plugin. The drupal module define a filter for {'image:id:relativepath:width} and {'imagedata:selector:type:timeout}

Normally the jquery plugin is used this way:

function func1(e,el){
  alert(el.tagName);
}
function func2(e,el){
  alert(el.tagName);
}
$(document).ready(function(){
  $(".linkimgs").contextmenu({'option 1':func1,
                              'option 2':func2},
                             'hold',1000);
});

with first parameter being the menu object (property name:function), second parameter type, could be right (right click), hold (hold down left button for timeout) or hover (stay hover element for timeout). Third parameter is timeout, used in hold, hover.

The callback menu function is called with event jquery object (the event is the click on context menu) and the element to which is attached the menu.

The menu is a ul with id “contextmenu”, this could be changed via $.contextmenu var, but it is an id because there must be only one context menu in a page, an example style is:

{syntaxhighlighter brush:css}
#contextmenu{
margin:0;
padding:0;
border: 1px solid #000;
background:#ccc;
}
#contextmenu li {
list-style-type:none;
margin:1px;
padding:2px;
cursor:pointer;
}
#contextmenu li.hover{
background: #ddd;
}
{/syntaxhighlighter}


Drupal example module (imagedata)

http://www.lullabot.com/articles/drupal-input-formats-and-filters is a good explanation of input filter in drupal and on how to configure it

The module define also a menu item for /imagedata/info/ that return image file info passed with the rest of the url

Javascript in module (contextmenu callback) is not complete, it works sizex and Zoom.

Example

Traditional context menu (right mouse button)
{‘imagedata:#target1:right}
{imagedata:#target1:right}
prato

Hold context menu (hold left mouse button for 1.5 seconds)
{‘imagedata:#target2:hold:1500}
{imagedata:#target2:hold:1500}
monte

Hover context menu (hover image with mouse for 2 seconds)
{‘imagedata:#target3:hover:2000}
{imagedata:#target3:hover:2000}
monte

About the images

The first photo (the valley landscape) is taken from Monte Cucco, Umbria.
The mountain in the other picture is near Laghi di Pilato, Sibillini, Marche.
Both shot by a Nokia N80 cellphone. You are free to use it.

Comments

What do you think about this plugin? there is something missing? things you would do better?

code and issues on github: https://github.com/danielecr/jquery-contextual-menu !

Update

2010-10-17: (Saint Catervus) fix problem with ie event model and scroll position fix for “event not normalized by jquery” case. Thanks Joe report.
2010-12-23: fix problem with nested context menu: stop propagation. Fearnloath report.
2011-01-14: return selection object for jquery chaining. Thanks to Patrick Corcoran
2011-01-14 (later):fixed opera bug (Maciej Pilarczyk)


Simplepie and CodeIgniter

yes, found: http://www.haughin.com/code/simplepie/
and tried with php 5.3 installation … simply do not work

I recalled there was a problem in simplepie for assign new by reference, just downloaded newer code from http://simplepie.org/ … still same problem.

So

{syntaxhighlighter brush:bash}
sed ‘s/=&\ new/=\ new/’ simplepie.inc > Simplepie.php
{/syntaxhighlighter}

adding if ( ! defined('BASEPATH')) exit('No direct script access allowed'); to first line, removing ?> from last line, make things work.

Some comment on new by reference are in http://php.net/manual/en/language.references.php

On why and where reference are bad there is a beautiful article: http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

and another on “strange” things that could happen: http://schlueters.de/blog/archives/141-References-and-foreach.html

Introduzione a JavaScript – Terza parte

Una video introduzione al linguaggio javascript e le sue principali caratteristiche

In questa terza parte: gli eventi.

Nota: gli eventi si propagano dal document fino al target e dal target fino al document (non al body)

La documentazione di call e apply da mozilla

Oggetti e ereditarietà in javascript sono presentati in
http://www.howtocreate.co.uk/tutorials/javascript/objects

Un semplice esempio che usa prototype in
http://snippets.dzone.com/posts/show/899

DOM Level 2 Event Model è documentato in http://www.w3.org/TR/DOM-Level-2-Events/events.html

Un ottima e completa guida e riferimento al linguaggio JavaScript è JavaScript. The Definitive Guide

Concetti object oriented e design pattern applicati al linguaggio javascript sono molto ben presentati in Pro JavaScript Design Patterns

La pagina di esempio utilizzata:
test.html

La prima parte
La seconda parte

Introduzione a JavaScript – Seconda parte

Una video introduzione al linguaggio javascript e le sue principali caratteristiche

In questa seconda parte: oggetti, il DOM, un esempio concreto, le closure

La documentazione di call e apply da mozilla

Oggetti e ereditarietà in javascript sono presentati in
http://www.howtocreate.co.uk/tutorials/javascript/objects

Un semplice esempio che usa prototype in
http://snippets.dzone.com/posts/show/899

DOM Level 2 Event Model è documentato in http://www.w3.org/TR/DOM-Level-2-Events/events.html

Un ottima e completa guida e riferimento al linguaggio JavaScript è JavaScript. The Definitive Guide

Concetti object oriented e design pattern applicati al linguaggio javascript sono molto ben presentati in Pro JavaScript Design Patterns

La pagina di esempio utilizzata:
test.html

La prima parte
La terza parte

Introduzione a JavaScript – Prima parte

Una breve introduzione al linguaggio e le principali caratteristiche dello scripting client side per il web

Presentati sinteticamente: sintassi, JSON, Object, DOM, Eventi

Oggetti e ereditarietà in javascript sono presentati in
http://www.howtocreate.co.uk/tutorials/javascript/objects

Un semplice esempio che usa prototype in
http://snippets.dzone.com/posts/show/899

DOM Level 2 Event Model è documentato in http://www.w3.org/TR/DOM-Level-2-Events/events.html

Un ottima e completa guida e riferimento al linguaggio JavaScript è JavaScript. The Definitive Guide

Concetti object oriented e design pattern applicati al linguaggio javascript sono molto ben presentati in Pro JavaScript Design Patterns

La seconda parte
La terza parte

shuffle db table order

simple code to shuffle a table … with php shuffle:

$result = $mysql->query("SELECT id FROM $table ORDER BY id");
$rows = $result->num_rows;
$order = shuffle(range(1,$rows));
while($row=$result->fetch_row()) {
  $num=array_shift($order);
  $mysql->query("UPDATE $table SET rand_sort=$num WHERE id=".$row[0]);
}

added:
with MySQL RAND():

$result = $mysql->query("SELECT id FROM $table ORDER BY RAND()");
for($i=1;$row=$result->fetch_row();$i++) {
  $mysql->query("UPDATE $table SET rand_sort=$i WHERE id=".$row[0]);
}

comments?

Ajax frontend for my backoffice in jQuery and PHP

This is my way to organize php for a simple jQuery frontend ajax based:

1.in a administration page include the php that generate html for each box
2.for each box setup behavior in Javascript
3.let each php manage POST request (for change/update) and GET request for show content


So in admin.php we could have something like that

<img src=”button.png” id=”btn_change” />
<div id=”box-profilo”>
<?php include “box-profilo.php”>
</div>

For setup behavior in javascript I use jQuery and an utility function (in admin.php):

CheckForm = function(d,f,o){return f.valid();};
   function addModBehav(link,div,url,form,cancel) {
   var revert = function() {
     $(div).load(url,function(){
	 $(link).show();
       });
   }
   $(link).click(function(){
       $(div).load(url+"?method=modify",
		   function(){
		     $(link).hide();
		     $(form).ajaxForm({target:div,
			   beforeSubmit:CheckForm,
			   success:function(){$(link).show();}});
		     $(cancel).click(revert);
		   });
       return false;
     });
 }
   $(function(){
       addModBehav("#btn_change","#box-profilo",
		   'box-profilo.php',"#form_profilo",
		   "#cancel");
});

box-profilo.php contains something like

<?php
if(isset($_POST['save'])) {
// save code
}
$method='view';
if(isset($_GET['method'])) {
$method=$_GET['method'];
}
if(method =='modify') {
?>
<form id=”form_profilo” action=”box-profilo.php” method=”post”>
….
<input type=”button” id=”cancel” />
</form>
<?php
} else {
// show data
}
?>


Used plugins:
ajaxForm plugin for function ajaxForm()
Validation plugin for function valid() (in CheckForm)

Fix SEO problem in drupal (give 301 to node/xx request)

this was a problem with www.tecnomagazine.it :

http://www.tecnomagazine.it/recensioni/casio-exilim_ex-z60/442

could be accessed from /node/442

Solution is to redirect all /node/[0-9]* url to the aliased one
… and is very simple in code:

includes/path.inc :

function drupal_init_path() {
  if (!empty($_GET['q'])) {
    // add this conditional
    if(preg_match('/node\/[0-9]*$/',$_GET['q'])) {
      include "includes/common.inc";
      $newq = trim(url($_GET['q']),'/');
      if($newq!=$_GET['q']) {
	drupal_goto(trim($_GET['q'],'/'),NULL,NULL,301);
      }
    }
    $_GET['q'] = drupal_get_normal_path(trim($_GET['q'], '/'));
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }
}

drupal_init_path() is called in bootstrap as sixth pass and find the internal path (like /node/[0-9]*)
Here I check if the request contains already a normal path, check if there is
aliased path, if so goto that path and give 301

update (16 August, 2010)
is better to use this (add conditional and goto) in custom_url_rewrite_inbound() function:
http://api.drupal.org/api/function/custom_url_rewrite_inbound/6
and do not touch drupal main code

see also
http://drupal.org/project/globalredirect

skype for linux 2.1 beta: 64 bit?

http://www.skype.com/download/skype/linux/

released skype for linux 2.1, I followed link and downloaded 64 bit version for ubuntu .. but look at package control:

Package: skype
Status: install ok installed
Priority: extra
Section: non-free/net
Installed-Size: 25096
Maintainer: Skype Technologies
Architecture: amd64
Version: 2.1.0.47-1
Depends: lib32stdc++6 (>= 4.1.1-21), lib32asound2 (>> 1.0.14), ia32-libs (>= 1.6), libc6-i386 (>= 2.7-1), lib32gcc1 (>= 1:4.1.1-21+ia32.libs.1.19)

Umh, a tricky way to make amd64 package …