Hover on dynamic link generated - javascript

I want to create a hover similar to the example here in the jQuery. But the link is dynamically generated so I'm really having a hard time figuring this out.
I tried this:
$(document).ready( function() {
$('a.g-tabs').on('hover', 'a', function() {
$( this ).append( $('<i class="icon-clear-remove" onClick="tabRemove();"></i>') );
},
function() {
$( this ).find( ".icon-clear-remove:last" ).remove();
});
});
But its not working. Seems like my selector is the problem. How can I select it properly?
UPDATE:
This JS is handles for the view to not refresh if the tab is created:
$(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();
});
Not this one is the HTML that handles the tabs if the user goes to this page in first hand:
<!-- Other tabs from the database -->
<c:forEach var="tabNames" items="${ allTabs }">
<li> ${ tabNames.key }</li>
</c:forEach>
<!-- Add new tab -->
<li>New <i class="icon-plus-sign"></i></li>
As requested the server side code:
#ResponseBody
#RequestMapping( value = "/admin/FLT_add_tab", method = RequestMethod.POST )
public String createNewTab( #RequestParam
String newTab, HttpServletRequest request )
{
HttpSession session = request.getSession();
String returnVal = Credentials.checkSession( session );
if( returnVal != null )
{
return returnVal;
}
String tabName = null;
try
{
DataSource dataSource = DatabaseCommunication.getInstance().getDataSource();
QuestionnaireDAO qDAO = new QuestionnaireDAO( dataSource );
if( qDAO.getTabName( 0, newTab ) == null )
{
qDAO.insertQtab( newTab );
tabName = newTab;
}
}
catch( Exception e )
{
// no logger yet
e.printStackTrace();
}
return tabName;
}

If it is dynamically created the you have to use the delegate
$(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();
});

try this code
$('a.g-tabs').on({
mouseenter: function() {
$( this ).append( $('<i class="icon-clear-remove" onClick="tabRemove();"></i>') );
},
mouseleave: function() {
$( this ).find( ".icon-clear-remove:last" ).remove();
}
}, "a");
this code from Is it possible to use jQuery .on and hover

use CSS.
.g-tabs a>.icon-clear-remove
{
display:none;
}
.g-tabs a:hover>.icon-clear-remove
{
display:inline-block;
}
E > F Matches any F element that is a child of an element E.
E:hover Matches E during user hovers E.
So, E:hover>F means that while user hovers E, apply rule to F.
Try it here http://jsfiddle.net/7bVTj/

Related

Woocommerce "Add to cart" ajax

On the product category page, when someone clicks "Add to cart", woocommerce adds "View cart" below this button through Ajax. I found that the script which handle this is /assets/js/frontend/add-to-cart.js
Now, I want to add also "Procceed to checkout", so someone can go to checkout immediately.
This is the output of the script:
jQuery( function( $ ) {
// wc_add_to_cart_params is required to continue, ensure the object exists
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
// Ajax add to cart
$( document ).on( 'click', '.add_to_cart_button', function(e) {
// AJAX add to cart request
var $thisbutton = $( this );
if ( $thisbutton.is( '.product_type_simple' ) ) {
if ( ! $thisbutton.attr( 'data-product_id' ) )
return true;
$thisbutton.removeClass( 'added' );
$thisbutton.addClass( 'loading' );
var data = {
action: 'woocommerce_add_to_cart',
};
$.each( $thisbutton.data(), function( key, value ) {
data[key] = value;
});
// Trigger event
$( 'body' ).trigger( 'adding_to_cart', [ $thisbutton, data ] );
// Ajax action
$.post( wc_add_to_cart_params.ajax_url, data, function( response ) {
if ( ! response )
return;
var this_page = window.location.toString();
this_page = this_page.replace( 'add-to-cart', 'added-to-cart' );
if ( response.error && response.product_url ) {
window.location = response.product_url;
return;
}
// Redirect to cart option
if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) {
window.location = wc_add_to_cart_params.cart_url;
return;
} else {
$thisbutton.removeClass( 'loading' );
fragments = response.fragments;
cart_hash = response.cart_hash;
// Block fragments class
if ( fragments ) {
$.each( fragments, function( key, value ) {
$( key ).addClass( 'updating' );
});
}
// Block widgets and fragments
$( '.shop_table.cart, .updating, .cart_totals' ).fadeTo( '400', '0.6' ).block({
message: null,
overlayCSS: {
opacity: 0.6
}
});
// Changes button classes
$thisbutton.addClass( 'added' );
// View cart text
if ( ! wc_add_to_cart_params.is_cart && $thisbutton.parent().find( '.added_to_cart' ).size() === 0 ) {
$thisbutton.after( ' <a href="' + wc_add_to_cart_params.cart_url + '" class="added_to_cart wc-forward" title="' +
wc_add_to_cart_params.i18n_view_cart + '">' + wc_add_to_cart_params.i18n_view_cart + '</a>' );
}
// Replace fragments
if ( fragments ) {
$.each( fragments, function( key, value ) {
$( key ).replaceWith( value );
});
}
// Unblock
$( '.widget_shopping_cart, .updating' ).stop( true ).css( 'opacity', '1' ).unblock();
// Cart page elements
$( '.shop_table.cart' ).load( this_page + ' .shop_table.cart:eq(0) > *', function() {
$( '.shop_table.cart' ).stop( true ).css( 'opacity', '1' ).unblock();
$( 'body' ).trigger( 'cart_page_refreshed' );
});
$( '.cart_totals' ).load( this_page + ' .cart_totals:eq(0) > *', function() {
$( '.cart_totals' ).stop( true ).css( 'opacity', '1' ).unblock();
});
// Trigger event so themes can refresh other areas
$( 'body' ).trigger( 'added_to_cart', [ fragments, cart_hash, $thisbutton ] );
}
});
return false;
}
return true;
});
Is there anybody who has done something similar?
If you look here from the Woocommerce repo, you can see that add-to-cart.js is localized from that class.
Unfortunately, there isn't a filter to just add your own link. What you could try is copying add-to-cart.js to your theme and set the new src of the registered add-to-cart.js to your new local copy, by using this method.
From there you can alter the this conditional found in Woocommerce repo.
So, technically yes, you could could this, but there are caveats:
You would need to repeat this process for variation products
If translation is a concern, you need to address that as well
Any time the plugin updates, you now have to comb through these files for any differences that could break functionality or cause a security issue.

$(document).on("click",".class_name",function() not working

Here is the HTML
<div id="menu" class='rmm' data-menu-title="Description">
<ul>
<li>Description</li>
<li>Features</li>
<li>Ratings</li>
<li>Activate</li>
</ul>
</div>
jquery portion to change menu title
function getMobileMenu() {
/* build toggled dropdown menu list */
$('.rmm').each(function() {
var menutitle = $(this).attr("data-menu-title");
if ( menutitle == "" ) {
menutitle = "Menu";
}
else if ( menutitle == undefined ) {
menutitle = "Menu";
}
var $menulist = $(this).children('.rmm-main-list').html();
var $menucontrols ="<div class='rmm-toggled-controls'><div class='rmm-toggled-title'>" + menutitle + "</div><div class='rmm-button'><span> </span><span> </span><span> </span></div></div>";
$(this).prepend("<div class='rmm-toggled rmm-closed'>"+$menucontrols+"<ul>"+$menulist+"</ul></div>");
});
}
I just want the menu title to be changed when I click the menu.
I tried the below but it won't work
$(document).on("click",".rmm_li_item",function()
var ctxt=this.innerHTML;
$(".rmm-toggled-title").text(ctxt);
})
complete design : responsivemobilemenu.com/en/
the code may syntax error you have missed callback function stating braket {, try this code
$(document).on("click",".rmm_li_item",function(e){
e.preventDefault();
var ctxt=this.innerHTML;
$(".rmm-toggled-title").text(ctxt);
})
Although add e.preventDefault() to stop reloading page
There seems to be some error in your on Click event.General syntax is for onClick event is
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
According to the question is this what you need?
$(document).on("click",".rmm_li_item",function(e){
e.preventDefault()
var ctxt=this.innerHTML;
$(".rmm").text(ctxt);
})
IF not please make a JSFIDDLE and share the link I could not comprehend what you said

Jquery Mobile 1.4 swipe demo in Chrome with mobile device

My question concerns the swipe event on a mobile device (I'm using a Nexus 7) with Chrome. I am working off the Jquery Mobile 1.4.2 demo which can be found here:
http://demos.jquerymobile.com/1.4.2/swipe-page/
I'll ask my question and copy the sample javascript below. I can get everything to work, both on my laptop (using Chrome) and on my tablet (using Firefox), but the swipe works maybe one out of ten times in Chrome with my tablet. Any advice? Thanks!
// Pagecreate will fire for each of the pages in this demo
// but we only need to bind once so we use "one()"
$( document ).one( "pagecreate", ".demo-page", function() {
// Initialize the external persistent header and footer
$( "#header" ).toolbar({ theme: "b" });
$( "#footer" ).toolbar({ theme: "b" });
// Handler for navigating to the next page
function navnext( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", next + ".html", {
transition: "slide"
});
}
// Handler for navigating to the previous page
function navprev( prev ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", prev + ".html", {
transition: "slide",
reverse: true
});
}
// Navigate to the next page on swipeleft
$( document ).on( "swipeleft", ".ui-page", function( event ) {
// Get the filename of the next page. We stored that in the data-next
// attribute in the original markup.
var next = $( this ).jqmData( "next" );
// Check if there is a next page and
// swipes may also happen when the user highlights text, so ignore those.
// We're only interested in swipes on the page.
if ( next && ( event.target === $( this )[ 0 ] ) ) {
navnext( next );
}
});
// Navigate to the next page when the "next" button in the footer is clicked
$( document ).on( "click", ".next", function() {
var next = $( ".ui-page-active" ).jqmData( "next" );
// Check if there is a next page
if ( next ) {
navnext( next );
}
});
// The same for the navigating to the previous page
$( document ).on( "swiperight", ".ui-page", function( event ) {
var prev = $( this ).jqmData( "prev" );
if ( prev && ( event.target === $( this )[ 0 ] ) ) {
navprev( prev );
}
});
$( document ).on( "click", ".prev", function() {
var prev = $( ".ui-page-active" ).jqmData( "prev" );
if ( prev ) {
navprev( prev );
}
});
});
$( document ).on( "pageshow", ".demo-page", function() {
var thePage = $( this ),
title = thePage.jqmData( "title" ),
next = thePage.jqmData( "next" ),
prev = thePage.jqmData( "prev" );
// Point the "Trivia" button to the popup for the current page.
$( "#trivia-button" ).attr( "href", "#" + thePage.find( ".trivia" ).attr( "id" ) );
// We use the same header on each page
// so we have to update the title
$( "#header h1" ).text( title );
// Prefetch the next page
// We added data-dom-cache="true" to the page so it won't be deleted
// so there is no need to prefetch it
if ( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", next + ".html" );
}
// We disable the next or previous buttons in the footer
// if there is no next or previous page
// We use the same footer on each page
// so first we remove the disabled class if it is there
$( ".next.ui-state-disabled, .prev.ui-state-disabled" ).removeClass( "ui-state-disabled" );
if ( ! next ) {
$( ".next" ).addClass( "ui-state-disabled" );
}
if ( ! prev ) {
$( ".prev" ).addClass( "ui-state-disabled" );
}
});
I've done the same experiment and I've observed similar results with my tablet (Nexus 7 - Google Chrome).
You should not use heavy frameworks like jQueryMobile if you are going to create a web app or a mobile website because even if these tools make your life easier at the end the result, especially on Android devices, will be slow and sluggish.
In other words you should create your own .css and .js.
If you need to manipulate the DOM very often you should also look for alternatives to jQuery.
I suggest that you use Zepto.js.
In the end, I decided to use the jQuery touchSwipe plugin and write my own code, works fine in different browsers and across devices. Some of this may not make sense without the HTML, but essentially I determine the direction of the swipe based on the variable that is passed into the method. Then, by getting various attributes and class names, I am turning on and off the display of the various divs that have previously loaded the JSON into them from another method. The way I do that is through substrings, where the last digit of the id is a number. If anyone has any comments about how this code could be more efficient, I'd be happy to hear your thoughts. Cheers.
function swipeLiterary() {
$("#read").swipe({
swipe:function(event, direction, distance, duration, fingerCount) {
switch (direction) {
case 'left':
var thisPage = $('.display').attr('id');
var nextPageNum = parseInt(thisPage.substring(8)) + 1;
var nextPage = thisPage.substring(0,8) + nextPageNum;
if (nextPageNum > 9) {
break
}
$('#' + thisPage).removeClass('display').addClass('nodisplay');
$('#' + nextPage).removeClass('nodisplay').addClass('display');
console.log(nextPage);
break;
case 'right':
var thisPage = $('.display').attr('id');
var prevPageNum = parseInt(thisPage.substring(8)) - 1;
var prevPage = thisPage.substring(0,8) + prevPageNum;
if (prevPageNum < 0){
break;
}
$('#' + thisPage).removeClass('display').addClass('nodisplay');
$('#' + prevPage).removeClass('nodisplay').addClass('display');
console.log(prevPage);
break;
case 'up':
console.log('up');
break;
}
//$(this).text("You swiped " + direction );
//console.log(this);
}
});
}

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(); }
});
}

Jquery Mobile Listview Autocomplete: how to trigger function when user presses enter?

I’m following the jquery mobile remote autocomplete demo:
http://jquerymobile.com/demos/1.3.0-beta.1/docs/demos/listviews/listview-filter-autocomplete.html
My list is being dynamically populated from my datasource fine and I can do things when the user clicks on a result from the list.
However I also need it to trigger a function when the user hits enter (or clicks “Go” on the phone)... How can I do this? Here's my current code:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "click","li",function() {
// do stuff when user clicks on item in list
alert('Doing stuff!');
});
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://mywebservice/"+$input.val(),
dataType: "json",
crossDomain: false
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li><a href='#'>" + val.display_name + "</a></li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
I've been searching alot for help, but most results have been talking about the jquery autocomplete and not the jquery mobile listview autocomplete...
Any help would be much appreciated -thanks!
Hey I used a local autocomplete jQM widget but this will work the same for ya -
HTML -
<div data-role="page" id="carPage">
<div data-role="content">
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a car..." data-filter-theme="d">
<li>Acura</li>
<li>Audi</li>
<li>BMW</li>
<li>Cadillac</li>
<li>Ferrari</li>
<li>Honda</li>
</ul>
</div>
</div>
JS -
$(function () {
$('#carPage input[data-type="search"]').on('keydown', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
alert('enter key was pressed');
}
});
});
jsFiddle Demo
/Update
Regarding the go button - Because the autocomplete widget wraps a form element around your content the go button will trigger a submit on the form. This means you can listen to the enter key press and go button press with this simple event handler like this below -
$("#carPage form").submit(function() {
// this will handle both the enter key and go button on device
});
I updated the jsFiddle demo with both approaches above. I like the second approach best because it handles both scenarios the easiest.

Categories

Resources