Related
I'm using a custom WooCommerce checkout.js file for a plugin I'm creating but I'm having an issue whereby the billing address is getting saved as the shipping address when the order is placed.
Here is the custom 'checkout.js' code:
/* global wc_checkout_params */
jQuery( function( $ ) {
// wc_checkout_params is required to continue, ensure the object exists
if ( typeof wc_checkout_params === 'undefined' ) {
return false;
}
console.log('Start');
$.blockUI.defaults.overlayCSS.cursor = 'default';
var wc_checkout_form = {
updateTimer: false,
dirtyInput: false,
xhr: false,
$order_review: $( '#order_review' ),
$checkout_form: $( 'form.checkout' ),
init: function() {
console.log('Init');
$( document.body ).bind( 'updated_checkout', this.updated_checkout );
$( document.body ).bind( 'update_checkout', this.update_checkout );
$( document.body ).bind( 'init_checkout', this.init_checkout );
$( document.body ).bind( 'country_to_state_changed', this.upgrade_state_fields );
$( document.body ).on( 'change', 'select.country_to_state, input.country_to_state', this.upgrade_state_fields );
$( '.back-to-checkout' ).bind( 'click', this.close_drawer );
// Payment methods
this.$checkout_form.on( 'click', 'input[name="payment_method"]', this.payment_method_selected );
if ( $( document.body ).hasClass( 'woocommerce-order-pay' ) ) {
this.$order_review.on( 'click', 'input[name="payment_method"]', this.payment_method_selected );
}
$( 'button.details-next-button' ).bind( 'click', this.prevent_checkout );
// Form submission
$( document.body ).on( 'click', '#place_order', this.submit );
this.$checkout_form.on( 'submit', this.submit );
// Inline validation
this.$checkout_form.on( 'blur change', '.input-text, select, input:checkbox', this.validate_field );
// Manual trigger
this.$checkout_form.on( 'update', this.trigger_update_checkout );
// Inputs/selects which update totals
this.$checkout_form.on( 'change', 'select.shipping_method, input[name^="shipping_method"], #ship-to-different-address input, .update_totals_on_change select, .update_totals_on_change input[type="radio"]', this.trigger_update_checkout );
this.$checkout_form.on( 'change', '.address-field select', this.input_changed );
this.$checkout_form.on( 'change', '.address-field input.input-text, .update_totals_on_change input.input-text', this.maybe_input_changed );
this.$checkout_form.on( 'change keydown', '.address-field input.input-text, .update_totals_on_change input.input-text', this.queue_update_checkout );
// Address fields
this.$checkout_form.on( 'change', '#ship-to-different-address input.mdl-switch__input', this.ship_to_different_address );
this.$checkout_form.on( 'change', '#order_notes input.mdl-switch__input', this.order_notes );
// Trigger events
this.$checkout_form.find( '#ship-to-different-address input' ).change();
this.init_payment_methods();
// Update on page load
if ( wc_checkout_params.is_checkout === '1' ) {
$( document.body ).trigger( 'init_checkout' );
}
if ( wc_checkout_params.option_guest_checkout === 'yes' ) {
$( 'input#createaccount' ).change( this.toggle_create_account ).change();
} else {
$( 'div.create-account' ).show();
}
jQuery('.woocommerce-message').remove();
},
init_payment_methods: function( selectedPaymentMethod ) {
console.log('Init payment_methods');
var $payment_methods = $( '.woocommerce-checkout' ).find( 'input[name="payment_method"]' );
// If there is one method, we can hide the radio input
if ( 1 === $payment_methods.length ) {
$payment_methods.eq(0).hide();
}
// If there was a previously selected method, check that one.
if ( selectedPaymentMethod ) {
$( '#' + selectedPaymentMethod ).prop( 'checked', true );
}
// If there are none selected, select the first.
if ( 0 === $payment_methods.filter( ':checked' ).length ) {
$payment_methods.eq(0).prop( 'checked', true );
}
// Trigger click event for selected method
$payment_methods.filter( ':checked' ).eq(0).trigger( 'click' );
wc_checkout_form.convert_payment_textinputs();
},
close_drawer: function() {
console.log('close_drawer');
jQuery('.mdl-layout__obfuscator.is-visible').click();
},
updated_checkout: function() {
console.log('updated_checkout');
jQuery('.mdl-layout__drawer .shipping input[type=radio]').each(function() {
var name = $(this).attr('name');
var id = $(this).attr('id');
$(this).attr('name','review_' + name);
$(this).attr('id','review_' + id);
});
componentHandler.upgradeDom();
window.setTimeout(function() {
jQuery('.mdl-textfield').each(function() {
if (!jQuery(this).is('.validate-required')) {
jQuery(this).removeClass('is-invalid');
}
if (jQuery(this).find('.mdl-textfield__input').val() != '') {
jQuery(this).addClass('is-dirty');
}
});
},10);
if (jQuery('.woocommerce-error').length > 0) {
var message ='';
jQuery('.woocommerce-error').find('li').each(function() {
message+= jQuery(this).text();
});
jQuery('.woocommerce-error').remove();
var snackbarContainer = document.querySelector('#error-snackbar');
var data = {
message: message,
timeout: 5000
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
}
jQuery('.woocommerce-message').remove();
},
convert_payment_textinputs: function() {
console.log('convert_payment_textinputs');
jQuery('.payment_box').find('input[type=text],input[type=tel],input[type=email],input[type=date],input[type=password]').each(function() {
if (jQuery(this).parent().is('[data-upgraded]') || jQuery(this).parent().find('input[type=text],input[type=tel],input[type=email],input[type=date],input[type=password]').length > 1) {
return;
}
jQuery(this).parent().addClass('mdl-textfield mdl-js-textfield mdl-textfield--floating-label');
jQuery(this).addClass('mdl-textfield__input');
jQuery(this).parent().find('label').addClass('mdl-textfield__label');
componentHandler.upgradeElement(jQuery(this).parent()[0]);
});
},
upgrade_state_fields: function() {
console.log('upgrade_state_fields');
$('#billing_state,#shipping_state').addClass('mdl-textfield__input');
$('#billing_state,#shipping_state,#billing_country, #shipping_country').each(function() {
jQuery(this).parent().removeAttr('data-upgraded');
jQuery(this).find('option[value=""]').text('');
componentHandler.upgradeElement(jQuery(this).parent()[0]);
});
window.setTimeout(function() {
jQuery('.mdl-textfield').each(function() { jQuery(this).find('.mdl-textfield__input').each(function() {
if (jQuery(this).val() && jQuery(this).val() != '') {
jQuery(this).parent().addClass('is-dirty');
} else {
jQuery(this).parent().removeClass('is-dirty');
}
if (jQuery(this).attr('placeholder') && jQuery(this).attr('placeholder') != '') {
jQuery(this).parent().addClass('has-placeholder');
} else {
jQuery(this).parent().removeClass('has-placeholder');
}
}); });
},100);
},
get_payment_method: function() {
console.log('get_payment_method');
return wc_checkout_form.$checkout_form.find( 'input[name="payment_method"]:checked' ).val();
},
payment_method_selected: function() {
console.log('payment_method_selected');
if ( $( '.payment_methods input.input-radio' ).length > 1 ) {
var target_payment_box = $( 'div.payment_box.' + $( this ).attr( 'ID' ) );
if ( $( this ).is( ':checked' ) && ! target_payment_box.is( ':visible' ) ) {
$( 'div.payment_box' ).filter( ':visible' ).slideUp( 250 );
if ( $( this ).is( ':checked' ) ) {
$( 'div.payment_box.' + $( this ).attr( 'ID' ) ).slideDown( 250 );
}
}
} else {
$( 'div.payment_box' ).show();
}
if ( $( this ).data( 'order_button_text' ) ) {
$( '#place_order' ).val( $( this ).data( 'order_button_text' ) );
} else {
$( '#place_order' ).val( $( '#place_order' ).data( 'value' ) );
}
},
toggle_create_account: function() {
console.log('toggle_create_account');
$( 'div.create-account' ).hide();
if ( $( this ).is( ':checked' ) ) {
$( 'div.create-account' ).slideDown();
}
},
init_checkout: function() {
console.log('init_checkout');
$( '#billing_country, #shipping_country, .country_to_state' ).change();
$( document.body ).trigger( 'update_checkout' );
},
maybe_input_changed: function( e ) {
console.log('maybe_input_changed');
if ( wc_checkout_form.dirtyInput ) {
wc_checkout_form.input_changed( e );
}
},
input_changed: function( e ) {
console.log('input_changed');
wc_checkout_form.dirtyInput = e.target;
wc_checkout_form.maybe_update_checkout();
},
queue_update_checkout: function( e ) {
console.log('queue_update_checkout');
var code = e.keyCode || e.which || 0;
if ( code === 9 ) {
return true;
}
wc_checkout_form.dirtyInput = this;
wc_checkout_form.reset_update_checkout_timer();
wc_checkout_form.updateTimer = setTimeout( wc_checkout_form.maybe_update_checkout, '1000' );
},
trigger_update_checkout: function() {
console.log('trigger_update_checkout');
wc_checkout_form.reset_update_checkout_timer();
wc_checkout_form.dirtyInput = false;
$( document.body ).trigger( 'update_checkout' );
},
maybe_update_checkout: function() {
console.log('maybe_update_checkout');
var update_totals = true;
if ( $( wc_checkout_form.dirtyInput ).length ) {
var $required_inputs = $( wc_checkout_form.dirtyInput ).closest( 'div' ).find( '.address-field.validate-required' );
if ( $required_inputs.length ) {
$required_inputs.each( function() {
if ( $( this ).find( 'input.input-text' ).val() === '' ) {
update_totals = false;
}
});
}
}
if ( update_totals ) {
wc_checkout_form.trigger_update_checkout();
}
},
ship_to_different_address: function() {
console.log('ship_to_different_address');
if ( $( this ).is( ':checked' ) ) {
$( '#shipping_address_section' ).slideDown();
} else {
$( '#shipping_address_section' ).slideUp();
}
},
order_notes: function() {
console.log('order_notes');
if ( $( this ).is( ':checked' ) ) {
$( '#order_notes_section' ).slideDown();
} else {
$( '#order_notes_section' ).slideUp();
}
},
reset_update_checkout_timer: function() {
console.log('reset_update_checkout_timer');
clearTimeout( wc_checkout_form.updateTimer );
},
validate_field: function() {
console.log('validate_field');
var $this = $( this ),
$parent = $this.closest( '.form-row' ),
validated = true;
if ( $parent.is( '.validate-required' ) ) {
if ( 'checklox' === $this.attr( 'type' ) && ! $this.is( ':checked' ) ) {
$parent.removeClass( 'woocommerce-validated' ).addClass( 'woocommerce-invalid woocommerce-invalid-required-field' );
validated = false;
} else if ( $this.val() === '' ) {
$parent.removeClass( 'woocommerce-validated' ).addClass( 'woocommerce-invalid woocommerce-invalid-required-field' );
validated = false;
}
}
if ( $parent.is( '.validate-email' ) ) {
if ( $this.val() ) {
/* https://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex */
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
if ( ! pattern.test( $this.val() ) ) {
$parent.removeClass( 'woocommerce-validated' ).addClass( 'woocommerce-invalid woocommerce-invalid-email' );
validated = false;
}
}
}
if ( validated ) {
$parent.removeClass( 'woocommerce-invalid woocommerce-invalid-required-field' ).addClass( 'woocommerce-validated' );
}
},
update_checkout: function( event, args ) {
console.log('update_checkout');
// Small timeout to prevent multiple requests when several fields update at the same time
wc_checkout_form.reset_update_checkout_timer();
wc_checkout_form.updateTimer = setTimeout( wc_checkout_form.update_checkout_action, '5', args );
},
update_checkout_action: function( args ) {
console.log('update_checkout_action');
if ( wc_checkout_form.xhr ) {
wc_checkout_form.xhr.abort();
}
if ( $( 'form.checkout' ).length === 0 ) {
return;
}
args = typeof args !== 'undefined' ? args : {
update_shipping_method: true
};
var country = $( '#billing_country' ).val(),
state = $( '#billing_state' ).val(),
postcode = $( 'input#billing_postcode' ).val(),
city = $( '#billing_city' ).val(),
address = $( 'input#billing_address_1' ).val(),
address_2 = $( 'input#billing_address_2' ).val(),
s_country = country,
s_state = state,
s_postcode = postcode,
s_city = city,
s_address = address,
s_address_2 = address_2;
has_full_address = true;
if ( $( '#ship-to-different-address' ).find( 'input' ).is( ':checked' ) ) {
s_country = $( '#shipping_country' ).val();
s_state = $( '#shipping_state' ).val();
s_postcode = $( 'input#shipping_postcode' ).val();
s_city = $( '#shipping_city' ).val();
s_address = $( 'input#shipping_address_1' ).val();
s_address_2 = $( 'input#shipping_address_2' ).val();
}
var data = {
security: wc_checkout_params.update_order_review_nonce,
payment_method: wc_checkout_form.get_payment_method(),
country: country,
state: state,
postcode: postcode,
city: city,
address: address,
address_2: address_2,
s_country: s_country,
s_state: s_state,
s_postcode: s_postcode,
s_city: s_city,
s_address: s_address,
s_address_2: s_address_2,
has_full_address: has_full_address,
post_data: $( 'form.checkout' ).serialize()
};
console.log(data);
if ( false !== args.update_shipping_method ) {
var shipping_methods = {};
$( 'select.shipping_method, input[name^="shipping_method"][type="radio"]:checked, input[name^="shipping_method"][type="hidden"]' ).each( function() {
shipping_methods[ $( this ).data( 'index' ) ] = $( this ).val();
} );
data.shipping_method = shipping_methods;
}
$( '.woocommerce-checkout-payment, .woocommerce-checkout-review-order-table' ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
wc_checkout_form.xhr = $.ajax({
type: 'POST',
url: wc_checkout_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'update_order_review' ),
data: data,
success: function( data ) {
var selectedPaymentMethod = $( '.woocommerce-checkout input[name="payment_method"]:checked' ).attr( 'id' );
// Reload the page if requested
if ( 'true' === data.reload ) {
window.location.reload();
return;
}
// Remove any notices added previously
$( '.woocommerce-NoticeGroup-updateOrderReview' ).remove();
var termsCheckBoxChecked = $( '#terms' ).prop( 'checked' );
window.fragmentss = data.fragments;
// Always update the fragments
if ( data && data.fragments ) {
$.each( data.fragments, function ( key, value ) {
$( key ).replaceWith( value );
$( key ).unblock();
} );
}
// Recheck the terms and conditions box, if needed
if ( termsCheckBoxChecked ) {
$( '#terms' ).prop( 'checked', true );
}
// Check for error
if ( 'failure' === data.result ) {
var $form = $( 'form.checkout' );
// Remove notices from all sources
$( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors returned by this event
if ( data.messages ) {
$form.prepend( '<div class="woocommerce-NoticeGroup-updateOrderReview">' + data.messages + '</div>' );
} else {
$form.prepend( data );
}
// Lose focus for all fields
$form.find( '.input-text, select, input:checkbox' ).blur();
// Scroll to top
$( 'html, body' ).animate( {
scrollTop: ( $( 'form.checkout' ).offset().top - 100 )
}, 1000 );
}
// Re-init methods
wc_checkout_form.init_payment_methods( selectedPaymentMethod );
// Fire updated_checkout e
$( document.body ).trigger( 'updated_checkout', [ data ] );
}
});
},
prevent_checkout: function(e) {
console.log('prevent_checkout');
console.log('clickprevent');
e.preventDefault();
},
submit: function(e) {
console.log('submit');
e.preventDefault();
wc_checkout_form.reset_update_checkout_timer();
var $form = $( wc_checkout_form.$checkout_form );
console.log('Form:' + $form);
if ( $form.is( '.processing' ) ) {
return false;
}
$( document )
.on(
'stripeError',
wc_checkout_form.updated_checkout
)
.on(
'checkout_error',
wc_checkout_form.updated_checkout
);
// Trigger a handler to let gateways manipulate the checkout if needed
if ( $form.triggerHandler( 'checkout_place_order' ) !== false && $form.triggerHandler( 'checkout_place_order_' + wc_checkout_form.get_payment_method() ) !== false ) {
$form.addClass( 'processing' );
var form_data = $form.data();
console.log ('Form Data:' + form_data );
if ( 1 !== form_data['blockUI.isBlocked'] ) {
$form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
// ajaxSetup is global, but we use it to ensure JSON is valid once returned.
$.ajaxSetup( {
dataFilter: function( raw_response, dataType ) {
// We only want to work with JSON
if ( 'json' !== dataType ) {
return raw_response;
}
try {
// Check for valid JSON
var data = $.parseJSON( raw_response );
if ( data && 'object' === typeof data ) {
// Valid - return it so it can be parsed by Ajax handler
return raw_response;
}
} catch ( e ) {
// Attempt to fix the malformed JSON
var valid_json = raw_response.match( /{"result.*"}/ );
if ( null === valid_json ) {
console.log( 'Unable to fix malformed JSON' );
} else {
console.log( 'Fixed malformed JSON. Original:' );
console.log( raw_response );
raw_response = valid_json[0];
}
}
return raw_response;
}
} );
console.log($form.serialize());
alert($form.serialize());
$.ajax({
type: 'POST',
url: wc_checkout_params.checkout_url,
data: $form.serialize(),
dataType: 'json',
This is the '$form.serialize()' data that is getting sent by the AJAX request:
billing_first_name=Testname&billing_last_name=Testlastname&billing_phone=0800000000&billing_email=test%40wpmad.com&billing_country=GB&billing_address_1=4+Test+Street&billing_address_2=&billing_city=Test+City&billing_state=Worcestershire&billing_postcode=DY11+1JR&shipping_first_name=Testname&shipping_last_name=Testlastname&shipping_company=&shipping_country=GB&shipping_address_1=99+Test+Street&shipping_address_2=&shipping_city=Worcester&shipping_state=Worcestershire&shipping_postcode=WR1+2DS&order_comments=&shipping_method%5B0%5D=free_shipping%3A1&terms=on&terms-field=1&_wpnonce=34d56c864b&_wp_http_referer=%2F%3Fwc-ajax%3Dupdate_order_review
As above, the order is placed, but the shipping address is replaced with the billing address on the order confirmation page and within the WooCommerce orders in the admin.
Any ideas why? Any help would be greatly appreciated!
Problem solved.
The issue was being caused as the checkbox in the WooCommerce checkout had been changed to a Google Material design checkbox/switch and was not setting the value of the checkbox to '1'.
Effectively, the $form.serialize() data didn't contain the ship_to_different_address=1 that is required in the WooCommerce AJAX request.
guys.
I'm trying develope a webpage which has draggable function.
I found a jQuery theme exactly I wanted, and I'm using that code.
I didnt modify a lot, but just added code that loads database using ajax and mysql.
After loading db, the draggable function doesnt work.
I think it's about the order of running the function.
so I used setTimeout on the function that has draggable function and it worked.
But the problem is that I have to load database every 5 seconds, so I cant keep using setTimeout for the draggable function everytime I load db.
Is there any solutions that I can fix this problem?
Here is the code that I use
main.php
$(document).ready(function database(){
if(window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("gallery").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","db.php",true);
xmlhttp.send();
init();
});
setTimeout(function (){
var $gallery = $("#gallery");
var $gallery2 = $("#gallery2");
var $trash = $("#trash");
var $trash2 = $("#trash2");
$("li",$gallery).draggable({
cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
});
$("li",$gallery2).draggable({
cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
});
$trash.droppable({
accept: "#gallery > li",
classes: {
"ui-droppable-active": "ui-state-highlight"
},
drop: function( event, ui ) {
deleteImage( ui.draggable );
}
});
$trash2.droppable({
accept: "#gallery2 > li",
classes: {
"ui-droppable-active": "ui-state-highlight"
},
drop: function(event, ui){
deleteImage2(ui.draggable);
}
});
$gallery.droppable({
accept: "#trash li",
classes: {
"ui-droppable-active":"custom-state-active"
},
drop: function(event, ui){
recycleImage(ui.draggable);
}
});
$gallery2.droppable({
accept: "#trash2 li",
classes: {
"ui-droppable-active":"custom-state-active"
},
drop: function(event, ui){
recycleImage2(ui.draggable);
}
});
var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";
function deleteImage( $item ) {
$item.fadeOut(function() {
var $list = $( "ul", $trash ).length ?
$( "ul", $trash ) :
$( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash );
$item.find( "a.ui-icon-trash" ).remove();
$item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
$item
.animate({ width: "100px" })
.find( "img" )
.animate({ height: "150px" });
});
});
}
function deleteImage2( $item ) {
$item.fadeOut(function() {
var $list = $( "ul", $trash2 ).length ?
$( "ul", $trash2 ) :
$( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash2 );
$item.find( "a.ui-icon-trash" ).remove();
$item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
$item
.animate({ width: "100px" })
.find( "img" )
.animate({ height: "150px" });
});
});
}
var trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";
function recycleImage( $item ) {
$item.fadeOut(function() {
$item
.find( "a.ui-icon-refresh" )
.remove()
.end()
.css( "width", "96px")
.append( trash_icon )
.find( "img" )
.css( "height", "72px" )
.end()
.appendTo( $gallery )
.fadeIn();
});
}
function recycleImage2( $item ) {
$item.fadeOut(function() {
$item
.find( "a.ui-icon-refresh" )
.remove()
.end()
.css( "width", "96px")
.append( trash_icon )
.find( "img" )
.css( "height", "72px" )
.end()
.appendTo( $gallery2 )
.fadeIn();
});
}
function viewLargerImage( $link ) {
var src = $link.attr( "href" ),
title = $link.siblings( "img" ).attr( "alt" ),
$modal = $( "img[src$='" + src + "']" );
if ( $modal.length ) {
$modal.dialog( "open" );
} else {
var img = $( "<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />" )
.attr( "src", src ).appendTo( "body" );
setTimeout(function() {
img.dialog({
title: title,
width: 400,
modal: true
});
}, 1 );
}
}
$( "ul.gallery > li" ).on( "click", function( event ) {
var $item = $( this );
var $target = $( event.target );
if ( $target.is( "a.ui-icon-trash" ) ) {
deleteImage( $item );
} else if ( $target.is( "a.ui-icon-zoomin" ) ) {
viewLargerImage( $target );
} else if ( $target.is( "a.ui-icon-refresh" ) ) {
recycleImage( $item );
}
return false;
});
$( "ul.gallery2 > li" ).on( "click", function( event ) {
var $item = $( this );
var $target = $( event.target );
if ( $target.is( "a.ui-icon-trash" ) ) {
deleteImage2( $item );
} else if ( $target.is( "a.ui-icon-zoomin" ) ) {
viewLargerImage( $target );
} else if ( $target.is( "a.ui-icon-refresh" ) ) {
recycleImage2( $item );
}
return false;
});
}, 1000);
db.php
<?php
$host = "localhost"; // 자신의 mysql
$DB_name = "master"; // 데이터베이스 이름
$user = "root"; // 기본 사용자.
$password = "0000"; // apm 기본 암호
$conn = mysqli_connect($host, $user, $password, $DB_name);
if(!$conn){
echo "fail!\n";
die('Could not connect: ' . mysqli_error($con));
}
//else
$sql = "select * from sensorlist";
$result = mysqli_query($conn,$sql);
$rowcnt = mysqli_num_rows($result);
$filed_name = array('S_Ultrasonic','S_IR','S_Humidity','S_Temperature','S_Heatindex','S_Light','S_Gas'); //센서 필드명 집합
if($rowcnt == 1){ //right (data가 1행만 들어있는 게 맞는 지 체크)
while($row = mysqli_fetch_array($result)){
for($i=0;$i<count($filed_name);$i++){
if($row[$filed_name[$i]] != NULL){
echo "<li class='ui-widget-content ui-corner-tr ui-draggable ui-draggable-handle'>";
echo "<h5 class='ui-widget-header'>" . $filed_name[$i] . "</h5>";
echo "<a href='images/high_tatras.jpg' title='View larger image' class='ui-icon ui-icon-zoomin'> View larger</a>";
echo "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a></li>";
}
}
}
//echo "No sensor";
} else if($rowcnt == 0) { //data가 하나도 없으면 없다고 출력
//없다고 출력
echo "No sensor";
} else { //이도 저도 아니면 땡!
//db 에러 출력
echo "No sensor";
}
mysqli_close($conn);
?>
Delegate you event if you have dynamically added elements, reinitialize your draggable plugin after the ajax is complete (do all your logic in the if of the onreadystatechange event)
I have a very simple menu, no sub menus and was curious how I would get the menu to close when I click on one of the links?
Plugin Home Page ->
Here is the code directly out of the .js file that comes in the zip when you download this menu. I really need to know what code to add and where to add it so that when I click a link it closes the menu.
;( function( $, window, undefined ) {
'use strict';
// global
var Modernizr = window.Modernizr, $body = $( 'body' );
$.DLMenu = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.DLMenu.defaults = {
// classes for the animation effects
animationClasses : { classin : 'dl-animate-in-1', classout : 'dl-animate-out-1' },
// callback: click a link that has a sub menu
// el is the link element (li); name is the level name
onLevelClick : function( el, name ) { return false; },
// callback: click a link that does not have a sub menu
// el is the link element (li); ev is the event obj
onLinkClick : function( el, ev ) { return false; }
};
$.DLMenu.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.DLMenu.defaults, options );
// cache some elements and initialize some variables
this._config();
var animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// animation end event name
this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu';
// transition end event name
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu',
// support for css animations and css transitions
this.supportAnimations = Modernizr.cssanimations,
this.supportTransitions = Modernizr.csstransitions;
this._initEvents();
},
_config : function() {
this.open = false;
this.$trigger = this.$el.children( '.dl-trigger' );
this.$menu = this.$el.children( 'ul.dl-menu' );
this.$menuitems = this.$menu.find( 'li:not(.dl-back)' );
this.$el.find( 'ul.dl-submenu' ).prepend( '<li class="dl-back">BACK</li>' );
this.$back = this.$menu.find( 'li.dl-back' );
},
_initEvents : function() {
var self = this;
this.$trigger.on( 'click.dlmenu', function() {
if( self.open ) {
self._closeMenu();
}
else {
self._openMenu();
}
return false;
} );
this.$menuitems.on( 'click.dlmenu', function( event ) {
event.stopPropagation();
var $item = $(this),
$submenu = $item.children( 'ul.dl-submenu' );
if( $submenu.length > 0 ) {
var $flyin = $submenu.clone().css( 'opacity', 0 ).insertAfter( self.$menu ),
onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' );
$item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classin );
self.$menu.addClass( self.options.animationClasses.classout );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
self.options.onLevelClick( $item, $item.children( 'a:first' ).text() );
} );
return false;
}
var link = $item.find('a').attr('href');
var hash = link.substring(link.indexOf('#')+1);
if( hash != "" ){
var elem = jQuery('div[data-anchor="'+hash+'"]');
autoScroll(elem);
self._closeMenu();
}else{
self.options.onLinkClick( $item, event );
}
} );
this.$back.on( 'click.dlmenu', function( event ) {
var $this = $( this ),
$submenu = $this.parents( 'ul.dl-submenu:first' ),
$item = $submenu.parent(),
$flyin = $submenu.clone().insertAfter( self.$menu );
var onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classout );
self.$menu.addClass( self.options.animationClasses.classin );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
$item.removeClass( 'dl-subviewopen' );
var $subview = $this.parents( '.dl-subview:first' );
if( $subview.is( 'li' ) ) {
$subview.addClass( 'dl-subviewopen' );
}
$subview.removeClass( 'dl-subview' );
} );
return false;
} );
},
closeMenu : function() {
if( this.open ) {
this._closeMenu();
}
},
_closeMenu : function() {
var self = this,
onTransitionEndFn = function() {
self.$menu.off( self.transEndEventName );
self._resetMenu();
};
this.$menu.removeClass( 'dl-menuopen' );
this.$menu.addClass( 'dl-menu-toggle' );
this.$trigger.removeClass( 'dl-active' );
if( this.supportTransitions ) {
this.$menu.on( this.transEndEventName, onTransitionEndFn );
}
else {
onTransitionEndFn.call();
}
this.open = false;
},
openMenu : function() {
if( !this.open ) {
this._openMenu();
}
},
_openMenu : function() {
var self = this;
// clicking somewhere else makes the menu close
$body.off( 'click' ).on( 'click.dlmenu', function() {
self._closeMenu() ;
} );
this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() {
$( this ).removeClass( 'dl-menu-toggle' );
} );
this.$trigger.addClass( 'dl-active' );
this.open = true;
},
// resets the menu to its original state (first level of options)
_resetMenu : function() {
this.$menu.removeClass( 'dl-subview' );
this.$menuitems.removeClass( 'dl-subview dl-subviewopen' );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.dlmenu = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( !instance ) {
logError( "cannot call methods on dlmenu prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for dlmenu instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) );
}
});
}
return this;
};
} )( jQuery, window );
After looking at their demo, it seems you can call method plugins. Replace dl-menu with the id of your menu.
$('#dl-menu a').click(function(e) {
$('#dl-menu').dlmenu('closeMenu');
});
I am trying to get stylesheet_directory in JS, but can't get it to work.
Here is what I have tried:
url : '<?php bloginfo('stylesheet_directory'); ?>/img/hamburger.svg'
AND:
var stylesheetDir = "<?php bloginfo('stylesheet_directory') ?>";
url : '$stylesheetDir/img/hamburger.svg',
I guess there is just a problem with some characters or something? Could you please help me out?
svgicons-config-js
var stylesheetDir = "<?php bloginfo('stylesheet_directory') ?>";
url == $stylesheetDir;
decodeURI(url);
var svgIconConfig = {
hamburgerCross : {
url : stylesheetDir + '/img/hamburger.svg',
animation : [
{
el : 'path:nth-child(1)',
animProperties : {
from : { val : '{"path" : "m 5.0916789,20.818994 53.8166421,0"}' },
to : { val : '{"path" : "M 12.972944,50.936147 51.027056,12.882035"}' }
}
},
{
el : 'path:nth-child(2)',
animProperties : {
from : { val : '{"transform" : "s1 1", "opacity" : 1}', before : '{"transform" : "s0 0"}' },
to : { val : '{"opacity" : 0}' }
}
},
{
el : 'path:nth-child(3)',
animProperties : {
from : { val : '{"path" : "m 5.0916788,42.95698 53.8166422,0"}' },
to : { val : '{"path" : "M 12.972944,12.882035 51.027056,50.936147"}' }
}
}
]
},
};
hamburger_animation.js
(function() {
[].slice.call( document.querySelectorAll( '.si-icons-default > .si-icon' ) ).forEach( function( el ) {
var svgicon = new svgIcon( el, svgIconConfig );
} );
new svgIcon( document.querySelector( '.si-icons-easing .si-icon-hamburger' ), svgIconConfig, { easing : mina.backin } );
new svgIcon( document.querySelector( '.si-icons-easing .si-icon-hamburger-cross' ), svgIconConfig, { easing : mina.elastic, speed: 600 } );
})();
svgicons.js
/**
* svgicons.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
/*** helper functions ***/
// from https://github.com/desandro/classie/blob/master/classie.js
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
function hasClass( el, c ) {
return 'classList' in document.documentElement ? el.classList.contains( c ) : classReg( c ).test( el.className )
}
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
// from http://stackoverflow.com/a/11381730/989439
function mobilecheck() {
var check = false;
(function(a){if(/(android|ipad|playbook|silk|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
// http://snipplr.com/view.php?codeview&id=5259
function isMouseLeaveOrEnter( e, handler ) {
if (e.type != 'mouseout' && e.type != 'mouseover') return false;
var reltg = e.relatedTarget ? e.relatedTarget :
e.type == 'mouseout' ? e.toElement : e.fromElement;
while (reltg && reltg != handler) reltg = reltg.parentNode;
return (reltg != handler);
}
/*** svgIcon ***/
function svgIcon( el, config, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this.svg = Snap( this.options.size.w, this.options.size.h );
this.svg.attr( 'viewBox', '0 0 64 64' );
this.el.appendChild( this.svg.node );
// state
this.toggled = false;
// click event (if mobile use touchstart)
this.clickevent = mobilecheck() ? 'touchstart' : 'click';
// icons configuration
this.config = config[ this.el.getAttribute( 'data-icon-name' ) ];
// reverse?
if( hasClass( this.el, 'si-icon-reverse' ) ) {
this.reverse = true;
}
if( !this.config ) return;
var self = this;
// load external svg
Snap.load( this.config.url, function (f) {
var g = f.select( 'g' );
self.svg.append( g );
self.options.onLoad();
self._initEvents();
if( self.reverse ) {
self.toggle();
}
});
}
svgIcon.prototype.options = {
speed : 200,
easing : mina.linear,
evtoggle : 'click', // click || mouseover
size : { w : 64, h : 64 },
onLoad : function() { return false; },
onToggle : function() { return false; }
};
svgIcon.prototype._initEvents = function() {
var self = this, toggleFn = function( ev ) {
if( ( ( ev.type.toLowerCase() === 'mouseover' || ev.type.toLowerCase() === 'mouseout' ) && isMouseLeaveOrEnter( ev, this ) ) || ev.type.toLowerCase() === self.clickevent ) {
self.toggle(true);
self.options.onToggle();
}
};
if( this.options.evtoggle === 'mouseover' ) {
this.el.addEventListener( 'mouseover', toggleFn );
this.el.addEventListener( 'mouseout', toggleFn );
}
else {
this.el.addEventListener( this.clickevent, toggleFn );
}
};
svgIcon.prototype.toggle = function( motion ) {
if( !this.config.animation ) return;
var self = this;
for( var i = 0, len = this.config.animation.length; i < len; ++i ) {
var a = this.config.animation[ i ],
el = this.svg.select( a.el ),
animProp = this.toggled ? a.animProperties.from : a.animProperties.to,
val = animProp.val,
timeout = motion && animProp.delayFactor ? animProp.delayFactor : 0;
if( animProp.before ) {
el.attr( JSON.parse( animProp.before ) );
}
if( motion ) {
setTimeout(function( el, val, animProp ) {
return function() { el.animate( JSON.parse( val ), self.options.speed, self.options.easing, function() {
if( animProp.after ) {
this.attr( JSON.parse( animProp.after ) );
}
if( animProp.animAfter ) {
this.animate( JSON.parse( animProp.animAfter ), self.options.speed, self.options.easing );
}
} ); };
}( el, val, animProp ), timeout * self.options.speed );
}
else {
el.attr( JSON.parse( val ) );
}
}
this.toggled = !this.toggled;
};
// add to global namespace
window.svgIcon = svgIcon;
})( window );
The site can be found here: http://goo.gl/wuUwUG
Please inspect element (or similar), and look at the code where it says "Failed to load resource: the server responded with a status of 404 (Not Found)"
Instead of:
url : '$stylesheetDir/img/hamburger.svg',
use
url : stylesheetDir + '/img/hamburger.svg',
EDIT
So, the following code is obsolete and unnecessary (it does nothing and can be removed):
url == $stylesheetDir;
decodeURI(url);
Feel free to remove it. Other than that everything looks fine.
I guess some more code is needed. You should reveal how you're using the svgIconConfig variable, and specifically, the url property.
EDIT
Thanks for revealing some more code. It appears that you're calling a <?php ... ?> block within a JS file. This block is not parsed by the server, so it is directly displayed instead of rendering the URL to the theme.
I'm not sure how you're enqueueing the scripts in the code, so I'll propose a solution that will work with any use case.
To fix this, insert the following in your theme functions.php
add_action('wp_head', 'my_js_var_stylesheet_directory', 9);
function my_js_var_stylesheet_directory() {
echo '<script type="text/javascript">';
echo 'var stylesheetDir = "' . get_bloginfo('stylesheet_directory') . '"';
echo '</script>';
}
and delete the top 3 lines from your svgicons-config-js file, as they are unnecessary.
From your code you have to echo the path for the css directory.
Check this one out :
var stylesheetDir = '<?php echo loginfo('stylesheet_directory') ; ?>/img/hamburger.svg';
console.log(stylesheetDir);
This is my website.
This is the JQuery code:
(function($){
var MSG_THANK_YOU = 'Thank you for voting!';
var MSG_CANT_VOTE = "You have already voted!";
var MSG_SELECT_ONE = "Please select one option!";
//-----------------------------------------------
// showTip
//-----------------------------------------------
var period_tip_window = 3000;
function showTip( obj, txt, bgcolor )
{
txt = typeof txt !== 'undefined' ? txt : "Saved!";
bgcolor = typeof bgcolor !== 'undefined' ? bgcolor : "#60a060";
var tip_box = obj.find( 'span[ttype="tip_box"]' ).clone();
if ( !tip_box.length )
{
var s = '';
s += "<span ";
s += "style='";
s += "text-align:center;";
s += "padding:10px;";
s += "margin:10px;";
s += "font-size:15px;";
s += "font-weight:bold;";
s += "font-style:italic;";
s += "font-family:times;";
s += "color:#ffffff;";
s += "background-color:" + bgcolor + ";";
s += "border:3px solid #cfcfcf;";
s += "border-radius: 15px;";
s += "-moz-border-radius: 15px;";
s += "-moz-box-shadow: 1px 1px 3px #000;";
s += "-webkit-box-shadow: 1px 1px 3px #000;";
s += "'>";
s += txt;
s += "</span>";
tip_box = $( s );
}
tip_box.css({
"position":"absolute",
"left":"-10000px",
"top":"-10000px"
});
tip_box.appendTo( $( 'body' ) );
tip_box.show();
wt = tip_box.outerWidth(false);
ht = tip_box.outerHeight(true);
var x = obj.offset().left;
var y = obj.offset().top;
var w = obj.width();
var h = obj.height();
var ytd = 10;
var xt = x + w/2 - wt/2;
var yt = y - ht;
tip_box.css( { "left":xt + "px", "top":yt + "px" } );
tip_box.fadeOut( period_tip_window, function() {
tip_box.remove();
});
}
//----------------------------------------------------------------
// CWaitIcon
//----------------------------------------------------------------
function CWaitIcon( url_img )
{
var s = '';
s += "<img ";
s += "src='" + url_img + "'";
s += ">";
this.img = $( s );
this.img.css({
"position":"absolute",
"left":"-10000px",
"top":"-10000px"
});
this.img.hide();
this.img.appendTo( $( 'body' ) );
}
CWaitIcon.prototype =
{
show : function( e )
{
var w = 32;
var h = 32;
this.img.css( { "left":(e.pageX - w/2) + "px",
"top":(e.pageY - h/2) + "px" } );
this.img.show();
},
hide : function()
{
this.img.hide();
}
}
//----------------------------------------------------------------
// CCookie
//----------------------------------------------------------------
function CCookie()
{
}
CCookie.prototype =
{
set : function( name, value, days )
{
days = days || 365;
var date = new Date();
date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
var expires = "; expires="+date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
},
get : function( name )
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0; i < ca.length; i++ )
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
del : function( name )
{
document.cookie = name + '=; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/';
}
}
var Cookie = new CCookie();
//----------------------------------------------------------------
// CAjaxPoll
//----------------------------------------------------------------
function CAjaxPoll( domobj )
{
this.domobj = domobj;
this.form = $( domobj );
this.tid = this.getAttr( 'tid', domobj );
this.b_front = true;
var action = this.getAttr( 'action', domobj );
this.url_server = action;
var pos = action.lastIndexOf("/");
var url_image = 'wait.gif';
if ( pos != -1 )
{
var path = action.substring( 0, pos+1 );
url_image = path + 'images/' + url_image;
}
this.wait_icon = new CWaitIcon( url_image );
}
CAjaxPoll.prototype =
{
//-----------------------------------------------
// getAttr
//-----------------------------------------------
getAttr : function( id_name, obj )
{
if (
( typeof( $( obj ).attr( id_name ) ) == 'undefined' ) ||
( $( obj ).attr( id_name ) == '' ) // for Opera
) return null;
return $( obj ).attr( id_name );
},
//-----------------------------------------------
// getCookieName
//-----------------------------------------------
getCookieName : function()
{
return 'ajax_poll_' + this.tid;
},
//-----------------------------------------------
// checkCookie
//-----------------------------------------------
checkCookie : function()
{
var key = this.getCookieName();
var s = Cookie.get( key );
if ( s == null )
{
Cookie.set( key, 'yes' );
$('.ajax-poll-btn-vote').css('display','none');
return true;
}
else
return false;
},
//-----------------------------------------------
// send
//-----------------------------------------------
send : function( item_tid )
{
var _this = this;
$.post( this.url_server,
{ cmd: "vote", form_tid:this.tid, item_tid:item_tid },
function(data) {
_this.wait_icon.hide();
var res = eval('(' + data + ')');
if ( res.result == 'OK' )
{
_this.items = res.items;
_this.displayStats();
}
else
{
alert( res.result );
}
});
},
//-----------------------------------------------
// run
//-----------------------------------------------
run : function()
{
var _this = this;
//-- [BEGIN] Row mouse over
this.form.find( '.ajax-poll-item' ).mouseover( function() {
$( this ).addClass( "ajax-poll-item-mover" );
}).mouseout( function() {
$( this ).removeClass( "ajax-poll-item-mover" );
});
//-- [END] Row mouse over
//-- [BEGIN] Setup radio buttons
this.form.find( '.ajax-poll-item , .ajax-poll-item-radio' ).each( function(){
var form_tid = _this.tid;
var item_tid = $(this).attr( 'tid' );
var radio = $(this).find( '.ajax-poll-item-radio' ).eq(0);
radio.attr( 'name', form_tid );
radio.attr( 'value', item_tid );
});
//-- [END] Setup radio buttons
//-- [BEGIN] Select an item
this.form.find( '.ajax-poll-item, .ajax-poll-item-radio' ).click( function(e){
//e.preventDefault();
if ( !_this.b_front ) return;
var tid = $(this).attr( 'tid' );
var radio = $(this).find( 'input[value="' + tid + '"]' );
radio.attr( 'checked', 'checked' );
_this.form.find( '.ajax-poll-item' )
.removeClass( "ajax-poll-item-sel" );
$(this).addClass( "ajax-poll-item-sel" );
});
//-- [END] Select an item
//-- [BEGIN] Vote
this.form.find( '.ajax-poll-btn-vote' ).click( function(e){
e.preventDefault();
var form = $(this).parents( '.ajax-poll-form' ).eq(0);
var item_tid = form.find( 'input[name="' + _this.tid + '"]:checked').val();
if ( typeof(item_tid) == 'undefined' ) item_tid = '';
if ( item_tid == '' )
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_SELECT_ONE, "#ff0000" );
return
}
else
{
if ( _this.checkCookie() )
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_THANK_YOU );
}
else
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_CANT_VOTE, "#ff0000" );
return;
}
}
_this.b_front = false;
form.find( '.ajax-poll-item-desc-box' ).hide();
form.find( '.ajax-poll-item-bar' ).css( 'width', 0 );
form.find( '.ajax-poll-item-count' ).html( '' );
form.find( '.ajax-poll-item-perc' ).html( '' );
form.find( '.ajax-poll-item-stats-box' ).show();
form.find( '.ajax-poll-vote-box' ).hide();
form.find('.ajax-poll-item-caption ').hide();
form.find('.ajax-poll-item-sel ').css('background','none');
form.find( '.ajax-poll-item-radio' ).hide();
_this.vote( e, item_tid );
});
//-- [END] Vote
//-- [BEGIN] View result
this.form.find( '.ajax-poll-btn-view' ).click( function(e){
e.preventDefault();
_this.b_front = false;
var form = _this.form;
form.find( '.ajax-poll-item-desc-box' ).hide();
form.find( '.ajax-poll-item-bar' ).css( 'width', 0 );
form.find( '.ajax-poll-item-count' ).html( '' );
form.find( '.ajax-poll-item-perc' ).html( '' );
form.find( '.ajax-poll-item-stats-box' ).show();
form.find( '.ajax-poll-vote-box' ).hide();
form.find('.ajax-poll-item-caption').hide();
form.find( '.ajax-poll-item-radio' ).hide();
form.find('.ajax-poll-item-sel ').css('background','none');
_this.vote( e, '' );
});
//-- [END] View result
//-- [BEGIN] Go Back
/*this.form.find( '.ajax-poll-btn-back' ).click( function(e){
e.preventDefault();
_this.b_front = true;
var form = _this.form;
form.find( '.ajax-poll-item-desc-box' ).show();
form.find( '.ajax-poll-item-stats-box' ).hide();
form.find( '.ajax-poll-vote-box' ).show();
form.find( '.ajax-poll-back-box' ).hide();
form.find( '.ajax-poll-item-radio' ).show();
});*/
//-- [END] Go Back
//-- [BEGIN] Reset cookie
/* this.form.next( '.ajax-poll-btn-reset' ).click( function(e){
e.preventDefault();
Cookie.del( _this.getCookieName() );
alert( "Cookie has been reset!" );
}); */
//-- [END] Reset cookie
},
//-----------------------------------------------
// vote
//-----------------------------------------------
vote : function( e, item_tid )
{
this.wait_icon.show(e);
this.send( item_tid );
},
//-----------------------------------------------
// displayStats
//-----------------------------------------------
displayStats : function()
{
var _this = this;
//-- [BEGIN] Calculate total & Find max count
var total = 0;
var max_cnt = 0;
this.form.find( '.ajax-poll-item' ).each( function(){
var item_tid = $(this).attr( 'tid' );
var cnt = 0;
if ( typeof(_this.items[item_tid]) != 'undefined' )
{
cnt = _this.items[item_tid];
}
else
{
_this.items[item_tid] = cnt;
}
if ( max_cnt < cnt ) max_cnt = cnt;
total += cnt;
});
this.form.find( '.ajax-poll-total-value' ).html( total.toString() + ' vote'
+ ( total == 1 ? '' : 's' ) );
//-- [END] Calculate total & Find max count
//-- [BEGIN] Find max width
var max_w = this.form
.find( '.ajax-poll-item' )
.eq(0)
.width();
max_w = parseInt( max_w );
//-- [END] Find max width
//-- [BEGIN] Show counts, percentage, and bar
this.form.find( '.ajax-poll-item' ).each( function(){
var tid = $(this).attr( 'tid' );
var cnt = ( typeof(_this.items[tid]) == 'undefined' ) ?
0 : _this.items[tid];
var perc = ( total > 0 ) ?
( ( cnt * 100 ) / total ) : 0;
$(this).find( '.ajax-poll-item-count' ).html( cnt.toString() + ' vote'
+ ( cnt == 1 ? '' : 's' ) );
$(this).find( '.ajax-poll-item-perc' ).html( perc.toFixed(1) + '%' );
if ( max_cnt > 0 )
{
var w = ( cnt * max_w ) / max_cnt;
var bar = $(this).find( '.ajax-poll-item-bar' );
bar.css( 'width', 300 );
bar.animate({
width: w
}, 1000 );
}
});
//-- [END] Show counts, percentage, and bar
}
}
//----------------------------------------------------------------
// ready
//----------------------------------------------------------------
$(document).ready(function() {
$( '.ajax-poll-form' ).each( function(){
var obj = new CAjaxPoll( this );
obj.run();
});
});
}(jQuery));
How do I first check on page load if the cookies exist for each form and if cookies exist do not display the ".ajax-poll-btn-vote " just the view button.
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
var cookie = getCookie("yourcookiename");
if (cookie != null) {
... your code here
}