jQuery UI - adding tabs tutorial need explanation - javascript

I'm having trouble understanding a certain part of the jQuery UI tabs tutorial. Specifically this part #{href}'>#{label} What is it doing/what does it mean?
Full code:
$(function () {
var tabTitle = $("#tab_title"),
tabContent = $("#tab_content"),
tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabCounter = 3;
var tabs = $("#tabs").tabs();
// modal dialog init: custom buttons and a "close" callback reseting the form inside
var dialog = $("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
Add: function () {
addTab();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
form[0].reset();
}
});
// addTab form: calls addTab function on submit and closes the dialog
var form = dialog.find("form").submit(function (event) {
addTab();
dialog.dialog("close");
event.preventDefault();
});
// actual addTab function: adds new tab using the input from the form above
function addTab() {
var label = tabTitle.val() || "Tab " + tabCounter,
id = "tabs-" + tabCounter,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label)),
tabContentHtml = tabContent.val() || "Tab " + tabCounter + " content.";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
tabCounter++;
}
// addTab button: just opens the dialog
$("#add_tab")
.button()
.click(function () {
dialog.dialog("open");
});
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});

You are putting this into a string:
<a href='#{href}'>#{label}</a>
And later on, you're taking that string and doing this with it:
tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label)
So what you're doing is replacing the {href} and {label} characters in the original string with the actual link and text for the <a> tag.

Basically, #{href} and #{label} as well as #tab_title and #tab_content are placeholders. These placeholders are replaced with the real content.
The jQuery UI tutorial holds some LI elements that will become the tabs afterwards:
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
You can match the content of href="" to the #{href} placeholder and the content of the A element will be inserted into the corresponding #{label}
The href-part even names the div-id that will contain the content.
<div id="tabs-1">
<p>Proin elit arcu, [... ]tempus lectus.</p>
</div>
The div with the id "tabs-1" will be read as the content for tab "#tabs-1". Inside the template, this content will be used in place of #tab_content.

Related

JQuery: Loading content into dynamic tabs with load()

I have a main menu, where if I click on any of the options a tab is dynamically created in a div. So I can create up to nine tabs of different options out there in the main menu.
The javascript code I use to create and delete tabs is as follows:
$(document).ready(function () {
$("#tabs").tabs();
var tabCounter = 1;
var cont =1;
var num_tabs = $("#tabs ul li").length +1,
tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabs = $( "#tabs" ).tabs();
// actual addTab function: adds new tab using the input from the form above
function addTab() {
var label = tabTitle || "Tab " + tabCounter,
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = "Tab " + tabCounter + " content.";
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'></div>" );
tabs.tabs( "refresh" );
cont++;
}
// close icon: removing the tab on click
tabs.delegate( "span.ui-icon-close", "click", function() {
var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
tabs.tabs( "refresh" );
cont--;
});
tabs.bind( "keyup", function( event ) {
if ( event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE ) {
var panelId = tabs.find( ".ui-tabs-active" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
tabs.tabs( "refresh" );
}
});
$(".menuitem a").click(function(event) {
event.preventDefault();
if(cont<=9)
{
tabTitle = $(this).attr("title"),
addTab();
$("#tabs-"+tabCounter).load($(this).attr('href'));
tabCounter++;
$("#tabs").tabs({active: $('.ui-tabs-nav li:last').index()});
}
else
{
$( "#dialog-message" ).dialog({
modal: true,buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
});
I wanted to get it by adding a tab is activated and show your content, so I added:
$("#tabs").tabs({active: $('.ui-tabs-nav li:last').index()});
Until there all right, I could show up to 9 tabs, but missing your content, it would be a path Symfony,for example:
<li class ="menuitem">test</li>
Then I added the following code to load this route into the div:
$("#tabs-"+tabCounter).load($(this).attr('href'));
And the result is that the content for each tab appears, but it only appears automatically activates the first tab does not show me the warning dialog that can not display more than 9 tabs. The code above is something that affects others and I can not get a solution to this problem.
Besides this problem, I need to know how to get that pressing an option from the main menu, if there is an open tab with that content to put the active tab and display its contents, instead of opening another like (there can be two tabs of the same content).
If there is a better way to do this, I would like to know.
I'm a newbie, so I apologize for how to explain it.

Jquery mobile swipe

I have tabs within a dynamic page. The tabs works great when pressed but I would like to add a swipe function to it so that users can also swipe to next tab.
Here is my attempt of trying to make the swipe function work
function goToMatchDetailPage(matchHome, matchAway){
first_part_id = matchHome.substring(0,2);
sec_part_id = matchAway.substring(0,2);
var id = first_part_id.concat(sec_part_id);
//create the html template
var matchPage = $("<div data-role='page' data-url=dummyUrl><div data-role='header'><h1>"
+ matchHome + "</h1></div><div data-role='content'><div data-role='tabs'>"
+ "<div data-role='navbar'>"
+ "<ul>"
+ "<li><a href='#fragment-1'>" + matchHome + "</a></li>"
+ "<li><a href='#fragment-2'>" + matchAway + "</a></li>"
+ "</ul>"
+ "</div>"
+ "<div id='fragment-1'>"
+ "<p>This is the content of the tab 'One', with the id fragment-1.</p>"
+ "</div>"
+ "<div id='fragment-2'>"
+ "<p>This is the content of the tab 'Two', with the id fragment-2.</p>"
+ "</div></div></div>");
//append the new page to the page contanier
matchPage.appendTo($.mobile.pageContainer);
//go to the newly created page
$.mobile.changePage(matchPage);
Here is the ppart that doesn't work
$(function(){
// Bind the swipeleftHandler callback function to the swipe event on div.box
$( "div" ).on( "swipeleft", swipeleftHandler );
// Callback function references the event target and adds the 'swipeleft' class to it
function swipeleftHandler( event ){
//go to the newly created page
$.mobile.changePage('#fragment-2');
}
});
}
!
Try using event delegation:
Because fragment-1 does not exist at the time you are creating the handler, you assign the handler to the document and delegate it to any child elements called fragment-1 that exist now or will exist in the future.
To make it more generic, you can assign classes to the div and delegate to the class instead of an id...
UPDATE
You can't use changepage to go between tabs, instead use the tabs widget active property(http://api.jqueryui.com/tabs/#option-active):
$(document).on("pagecreate", "#page1", function () {
$("#btngo").on("click", function(){
goToMatchDetailPage('Liverpool', 'Southhampton');
});
$(document).on("swipeleft", "#fragment-1", function(){
$(this).parents("div [data-role=tabs]").tabs( "option", "active", 1 );
} );
$(document).on("swiperight", "#fragment-2", function(){
$(this).parents("div [data-role=tabs]").tabs( "option", "active", 0 );
} );
});
Here is a DEMO
The swipe code is assigned to the document and then delegated to the dynamic div. When you swipe on a tab div, we find its parent that is the tab widget container and then set its active tab option to change tabs.
try this simple code
$(document).on("swipeleft", '#'+event.target.id, function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
alert(nextpage.attr('id'));
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$(document).on("swiperight", '#'+event.target.id, function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true }, true, true);
}
});
I'm easier than the others.. It's not the whole solution, but you can get my point.
Option 1
$(document).on("swipeleft", '#page1', function () {
$('#fragment-2').trigger('click');
});
Option 2
$(document).on("swipeleft", '#page1', function () {
$(this).find("div [data-role=tabs]").tabs( "option", "active", 1 );
});
Not sure about which one is better thought :)

Jquery events for closing and opening select drop down , and not on change

i want a neat solution to handle event for a drop down menu , so that when user opens the select menu , it alerts opened , and when he closes it , it alerts closed , neglecting wheather the selected value is changed or not.
<select id="dummy">
<option>dummy1</option>
<option>dummy2</option>
<option>dummy3</option>
</select>
what i want is something like
$("#dummy").on('open',function(){//do something})
$("#dummy").on('close',function(){//do something})
something like heapbox
http://www.bartos.me/heapbox/
and this solution is not acceptable : Run change event for select even when same option is reselected
the typical approach to extending the native functionality of a select box is to replace it with styleable markup and then tie the values of the new markup back into the origninal (now hidden) select element. (NOTE: I've not included any styles. This is a bare-bones example of using a select replacement).
var SelectBox = {
init: function () {
if ($('select').length > 0) {
this.generateStyledSelectbox('custom-select');
};
},
generateStyledSelectbox: function (cssClass) {
// Contained within .each to isolate all instances of <select>
$('select').each(function(index) {
var $source = $(this),
selected = $source.find("option[selected]"),
options = $source.find('option'),
selindex = index;
// Append styleable pseudo-select element to doc
$source.after('<div id="result-' + index + '" class="' + cssClass + '"></div>');
// Construct select list in pseudo select element
$('#result-' + index).append('<dl id="activeValue-' + index + '" class="dropdown"></dl>');
$('#activeValue-' + index).append('<dt>' + selected.text() + '<span class="value">' + selected.val() + '</span></dt>');
$('#activeValue-' + index).append('<dd><ul></ul></dd>');
// Assign select values to pseudo-select lis items
options.each(function () {
$('#activeValue-'+ index + ' dd ul').append('<li class="select-menu-item">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></li>');
});
$('.dropdown').each(function(index) {
$(this).find('dd ul li a').on('click', function(event) {
event.preventDefault();
var text = $(this).not('.value').html(),
$base = $('.custom-selectbox').eq(index);
$('.dropdown').eq(index).find('dt a').html(text);
$('.dropdown').eq(index).find('dd ul').hide();
$base.val($(this).find('span.value').html());
});
});
// prevent link actions in dropdown
$('.dropdown dt a').on('click', function (event) {
event.preventDefault();
});
// open/close
$(".dropdown").eq(index).find('dt a').on('click', function () {
$(".dropdown").eq(index).find('dd ul').toggle();
});
$(".dropdown").eq(index).find('dd ul li a').on('click', function () {
var text = $(this).html(),
newval = $(this).find('.value').html();
$(".dropdown").eq(index).find('dt a span').html(text);
$('select').eq(index).val(newval);
$(".dropdown").eq(index).find('dd ul').hide();
});
// Hide dropdown on outside click
$(document).on('click', function (e) {
var $clicked = $(e.target);
if (!$clicked.parents().hasClass("dropdown")) {
$(".dropdown").eq(index).find('dd ul').hide();
}
// remove dropdown-open targetable class
if (!$clicked.parents().hasClass("dropdown-open")) {
$clicked.parents().removeClass('dropdown-open');
}
});
// Hide native select
$source.css('display', 'none');
// assign initial (default) value
var initialval = $source.find('option').eq(0).html();
$('#activeValue-'+index+' dt a').html(initialval);
}); // END .each
}
};
SelectBox.init();
Here's a fiddle http://jsfiddle.net/P6ZCn/ (again, without styles)

Remove parent element jQuery

How can I remove all elements including its parent when click. The tabs is generated dynamically. What I tried so far is:
I'm using bootbox for the confirmation.
function remove() {
bootbox.confirm("Are you sure?", function(result) {
if( result != false ) {
var anchor = $(this).siblings('a');
$(anchor.attr('href')).remove();
$(this).parent().remove();
$(".nav-tabs li").children('a').first().click();
}
});
}
The tab that I will remove is generated through this:
$(document).on('submit','#pop-form', function(e) {
// make an ajax request
$.post('../admin/FLT_add_tab.do',
$('#pop-form').serialize(),
function( data ) {
// if data from the database is empty string
if( $.trim( data ).length != 0 ) {
// hide popover
$('#popover').popover('hide');
//append new tab and new tab content
var id = $(".nav-tabs").children().length - 1;
$('#popover').closest('li').before('<li>' + data + ' </li>');
$('.tab-content').append('<div class="tab-pane" id="tab_' + id + '"> <c:import url="flt-pis.html"></c:import> </div>');
} else {
// error handling later here
}
}
);
e.preventDefault();
});
UPDATE:
remove() is called by appending <i> when the user hover the tab
$(document).ready( function() {
$(document).on('mouseenter', 'a.g-tabs', function() {
$( this ).append( $('<i class="icon-clear-remove" onClick="tabRemove();"></i>') );
});
$(document).on('mouseleave', 'a.g-tabs', function() {
$( this ).find( ".icon-clear-remove:last" ).remove();
});
});
The JS that concern if the page is refreshed
<!-- Other tabs from the database -->
<c:forEach var="tabNames" items="${ allTabs }">
<li>${ tabNames.key } </li>
</c:forEach>
Popover for adding new tab
<!-- Add new tab -->
<li>New <i class="icon-plus-sign"></i></li>
The main problem is remove method does not know on which element it is getting called, I've changed the remove to use jQuery handler instead of inlined click handler.
Try
$(document).on('mouseenter', 'a.g-tabs', function () {
$(this).append($('<i class="icon-clear-remove"></i>'));
});
$(document).on('mouseleave', 'a.g-tabs', function () {
$(this).find(".icon-clear-remove:last").remove();
});
jQuery(function () {
$(document).on('click', '.icon-clear-remove', function () {
var $this = $(this);
bootbox.confirm("Are you sure?", function (result) {
if (result != false) {
alert('delete:' + $this[0].tagName)
var $a = $this.closest('.g-tabs');
alert($a.length)
$($a.attr('href')).remove();
$a.parent().remove();
$(".nav-tabs li").children('a').first().click();
}
});
})
})
I can't tell exactly how you are implementing this but if my guess is right this should work.
If it doesn't work, you should consider setting up a fiddle.
function remove() {
bootbox.confirm("Are you sure?", function(result) {
if (result) { $(this).remove(); }
});
}

Use 'this' to trigger a function when a Jquery tab is pressed

I am creating Jquery Tabs dynamically by passing in a viewName parameter. I am trying to figure out how to use this to trigger another function based on the id of the dynamically created Tab.
Here is function that creates the Tabs and assigneds them an ID and Name dynamically.
function SetImportedView(viewName, scriptValue) {
/* put the values we received in parameters into create view tabs*/
$('<li id="' + viewName + '">' + '<a href="' + '#tabs-1' + '"</a>' + viewName + '</li>').insertBefore('#new');
}
I need to trigger a another function that is specific to the ID of the Tab that is clicked.
something like this:
$(this.tab).click(function() {
doSomething
}
What's with this
function SetImportedView(viewName, scriptValue) {
/* put the values we received in parameters into create view tabs*/
$('<li id="' + viewName + '">' + '<a href="' + '#tabs-1' + '"</a>' + viewName + '</li>')
.on( 'click', 'a' function( ev ) {
// link in li clicked
} )
.insertBefore('#new');
}
edit
ok, you mean something like this?!?!
$( 'li' ).on( 'click', 'a', function( ev ) {
var tabID = $( this ).parent().attr('id');
// do something here with your tabID
} );
simply put an onclick on your "a" tag so it renders like this:
TAB #1
Solved...
$('#tabs ul li a').click(function() {
console.log($(this).attr('id'));
});

Categories

Resources