Jquery mobile swipe - javascript

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 :)

Related

stopping nested jquery ui tooltips

I am using the jquery ui tooltip extension. Given a link (level 1) of class "tooltips" it generates a tooltip whose content is a link (level 2), and since that link (level 2) also has class tooltips, it generates another tooltip (level 3) whose content is a link whose text is link= and the href of the original level 1 link.
So far so good. That much I want. (the original hrefs are very long, so I don't want them to appear in level 2)
What I want to do is not have that level 3 link generate another tooltip. How can I stop propagation at that level. I tried a variety of selectors, but nothing worked.
// modified from https://stackoverflow.com/a/15014759https://stackoverflow.com/a/15014759
$( document ).tooltip({
show: null, // null = show immediately
items: '.tooltips',
tooltipClass: 'tooltipstyle',
content: function () {
return "<a class='tooltips' target='_blank' href='" + $(this).prop('href')+ "' title='link=" + $(this).prop('href') + "' >" + $(this).prop('title') + "</a>" ;
},
hide: {
effect: "", // fadeOut
},
open: function( event, ui ) {
ui.tooltip.animate({ left: ui.tooltip.position().left - 25 }, "slow" );
},
close: function( event, ui ) {
ui.tooltip.hover(
function () {
$(this).stop(true).fadeTo(1600, 3);
//.fadeIn("slow"); // doesn't work because of stop()
},
function () {
$(this).fadeOut("1600", function(){ $(this).remove(); })
}
);
}
});

jQueryUI Sortable duplicating elements after reinitialising draggable

I am using a combination of JqueryUI Draggable and Sortable to select images from a grid and drag them into a sort-able container where they can be re ordered. the problem is when i load more images i need to reinitialise draggable to include the added items.
https://jsfiddle.net/Lpj8jthk/2/
Initialise Drag
function initDragAndDrop(){
$( ".ui-draggable" ).draggable({
opacity: 1.0,
helper: 'clone',
revert: 'invalid',
connectToSortable: '#drop-area'
});
$("#drop-area").sortable({
axis:"x",
connectWith: '.connectedSortable'
});
}
$( document ).ready(function() {
load_draggable_images(track_page); //load content
initDragAndDrop();
});
load more button handeler
$("#load-more-draggable-images").click(function (e) { //user clicks on button
track_page++; //page number increment everytime user clicks load button
load_draggable_images(track_page); //load content
initDragAndDrop();
});
function load_draggable_images(track_page){
// $('.animation_image').show(); //show loading image
$.post( 'includes/load-images.php', {'page': track_page}, function(data){
if(data.trim().length == 0){
//display text and disable load button if nothing to load
$("#load_more_button").text("No more records!").prop("disabled", true);
}
var parsed = JSON.parse(data);
// $("#images-container").empty();
$.each(parsed, function(k,v){
var name = v['filename'].split(".").shift()
var htmlString = "<div class='tile' data-timestamp='" + v['time']+ "'>" +
"<div>"+
"<img class='ui-draggable' src='" + v['thumbnail'] + "'> "+
"<p>" + name + "</p>"+
"</div> <br> "+
"</div> ";
$("#images-container").append(htmlString);
});
initDragAndDrop();
//scroll page to button element
// $("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 800);
//hide loading image
// $('.animation_image').hide(); //hide loading image once data is received
});
}
https://jsfiddle.net/Lpj8jthk/2/
In your success callback, I would perform:
$("#images-container").sortable("refresh");
Read More: http://api.jqueryui.com/sortable/#method-refresh
Update
From the fiddle, there are a few things I would suggest.
JavaScript
var track_page = 1;
function initDrag($t) {
$t.draggable({
opacity: 1.0,
helper: 'clone',
revert: 'invalid',
connectToSortable: '#drop-area'
});
}
function load_draggable_images(track_page) {
$("#adverts-container").append(makeImage("https://placehold.it/100x100", "ui-draggable"), makeImage("https://placehold.it/100x100", "ui-draggable"), makeImage("https://placehold.it/100x100", "ui-draggable"));
initDrag($("#adverts-container img"));
}
function makeImage(s, c) {
return $("<img>", {
src: s,
class: c
});
}
$(document).ready(function() {
load_draggable_images(track_page);
$("#drop-area").sortable({
axis: "x",
connectWith: '.connectedSortable'
});
initDrag($("#adverts-container img"));
$("#load-more-draggable-images").click(function(e) { //user clicks on button
console.log('Button Clicked');
track_page++; //page number increment everytime user clicks load button
load_draggable_images(track_page); //load content
});
});
There is an order of operations still, so it may be best to define your functions and global variable first. I removed the sortable from your first function, simply because you only have to set it once. The loading button I just made some minor changes to. And I created another function since you will be making a lot of images, why not make that a function.
Once the page has loaded and is ready, we can setup our elements. Load images, set sortable, set draggables, and finally program our click event.
So now you can pass a selector to initDrag() and the element or elements will become draggable and can be dragged into sortable. Sortable only allows x axis, so they can never be removed. You may want to consider a method for removing an image.

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)

Dynamic element under the droppable parent, over and out event not working properly

I have 2 columns, i made these 2 columns as droppable, when i "over" on any one of them, I am creating new "list" as it's children, and I am making children's as well droppable..
But i am not able to drop on the new children, I require to append the dragged list element to children element..
here is my function i wrote :
var generate = function (id) {
var id = "#" + id, c = 0, ul = $("<ul />");
$(id).empty();
while(c < 10 ) {
c ++;
ul.append($("<li />", { text : c + " new list"}));
}
return ul;
}
$("li").draggable({
revert:true,
helper: "clone"
});
$(".cl").droppable({
accept: "li",
activeClass : "highLight",
over: function( event, ui ) {
var elements = generate(event.target.id);
$("#" + event.target.id).append(elements);
$(".cl li").droppable({
over : function (event, ui ){
console.log("it is over now!"); // not working
},
drop : function () {
console.log ("dropped");
},
out : function () {
console.log ("I am out") // not working..
}
});
}
});
Here is the live demo
Any one help me to sort this issue.. and new children became droppable and appending a copy of draggable list..?
Thanks in Advance..
The problem is that you regenerating the top level children every time the mouse moves over the column. Fix it by adding this code at the top of your over: function:
if (event.target._generated)
return;
event.target._generated = true;
Here is the working FIDDLE: http://jsfiddle.net/eM8CX/

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