tags:

views:

301

answers:

3

Ok so i have some html like this:

<div id="navigation">

<ul>

<li>
<a>tab name</a>
<span class="delete-tab">X</span>
</li>

<li>
<a>tab name</a>
<span class="delete-tab">X</span>
</li>

<li>
<a>tab name</a>
<span class="delete-tab">X</span>
</li>

<li class="selected">
<a>tab name</a>
<span class="tab-del-btn">X</span>
</li>

</ul>

</div>

I then have javascript that is excuted on the page that i do not control (this is in liferay portal). I want to then manipulate things afterwards with my own custom javascript.

SO...

For each of the span.delete-tab elements an on-click event function has been assign earlier. It is the same function call for each span. I want to take that function (any) and call it from the click event of the span.tab-del-btn ?

This is what i tried to do:

var navigation = jQuery('#navigation');
var navTabs = navigation.find('.delete-tab');

var existingDeleteFunction = null;

navTabs.each(function (i){
        var tab = jQuery(this);
        existingDeleteFunction = tab.click;
});

var selectedTab = jQuery('#navigation li.selected');
var deleteBtn = selectedTab.find('.tab-del-btn');

deleteBtn.click(function(event){
        existingDeleteFunction.call(this);
});

It does not work though. existingDeleteFunction is not the original function it is some jquery default function.

Any ideas?

A: 

Try this:

var navTabs = $("#navigation .delete-tab:first");

$(".tab-del-btn","#navigation li.selected").click(function() {
    navTabs.click();
});

I shortened up the code for you too.

Willson Haw
A: 

Hi Wilson Haw

My fault but there was more information that i realised i left out. I need to remove the .delete-tab elements after i take one of the functions. Anyway after some poking around i found this that works. I would like to do it an few less lines of code though. Any ideas ?

var navigation = jQuery('#navigation');
var navTabs = navigation.find('.delete-tab');

var events = jQuery.data(navTabs.get(0), "events");
var clickEvents = events.click;

var existingDeleteFunction = null;

jQuery.each(clickEvents, function(i, val) {
    existingDeleteFunction = val;
});   

navTabs.each(function (i){
    var tab = jQuery(this);
    tab.remove();
});

var selectedTab = jQuery('#navigation li.selected');
var deleteBtn = selectedTab.find('.tab-del-btn');

deleteBtn.bind('click',existingDeleteFunction);
Peter Delahunty
A: 

You can shorten the code you posted down to this:

var clickEvents = jQuery('#navigation .delete-tab').data("events").click;
var btn = jQuery('#navigation li.selected .tab-del-btn');
jQuery.each(clickEvents, function(i, val) {
  btn.bind('click',val);
});
jQuery('#navigation .delete-tab').remove();

This will assign each click handler the original button has to the .tab-del-btn element, the functionality should be equivalent to the code you posted in the follow-up answer.

Nick Craver