I am building a web application that needs windows explorer-like feature. I have implemented jQuery File Tree but that one works for left navigation only. Any ideas that I can work on or any ready-made solutions out there?
Following is the PHP code that builds the ul and li tags:
if( file_exists($root . $_POST['dir']) ) {
$files = scandir($root . $_POST['dir']);
natcasesort($files);
if( count($files) > 2 ) { /* The 2 accounts for . and .. */
echo "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
// All dirs
foreach( $files as $file ) {
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && is_dir($root . $_POST['dir'] . $file) ) {
echo "<li class=\"directory collapsed\">" . htmlentities($file) . "</li>";
}
}
// All files
foreach( $files as $file ) {
if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) ) {
$ext = preg_replace('/^.*\./', '', $file);
echo "<li class=\"file ext_$ext\">" . htmlentities($file) . "</li>";
}
}
echo "</ul>";
}
}
Following is the jquery library
if(jQuery) (function($){
$.extend($.fn, {
fileTree: function(o, h) {
// Defaults
if( !o ) var o = {};
if( o.root == undefined ) o.root = '/';
if( o.script == undefined ) o.script = 'jqueryFileTree.php';
if( o.folderEvent == undefined ) o.folderEvent = 'click';
if( o.expandSpeed == undefined ) o.expandSpeed= 500;
if( o.collapseSpeed == undefined ) o.collapseSpeed= 500;
if( o.expandEasing == undefined ) o.expandEasing = null;
if( o.collapseEasing == undefined ) o.collapseEasing = null;
if( o.multiFolder == undefined ) o.multiFolder = true;
if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';
$(this).each( function() {
function showTree(c, t) {
$(c).addClass('wait');
$(".jqueryFileTree.start").remove();
$.post(o.script, { dir: t }, function(data) {
$(c).find('.start').html('');
$(c).removeClass('wait').append(data);
if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
bindTree(c);
});
}
function bindTree(t) {
$(t).find('LI A').bind(o.folderEvent, function() {
if( $(this).parent().hasClass('directory') ) {
if( $(this).parent().hasClass('collapsed') ) {
// Expand
if( !o.multiFolder ) {
$(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
$(this).parent().parent().find('LI.directory').removeClass('expanded').addClass('collapsed');
}
$(this).parent().find('UL').remove(); // cleanup
showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );
$(this).parent().removeClass('collapsed').addClass('expanded');
} else {
// Collapse
$(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
$(this).parent().removeClass('expanded').addClass('collapsed');
}
} else {
h($(this).attr('rel'));
}
return false;
});
// Prevent A from triggering the # on non-click events
if( o.folderEvent.toLowerCase != 'click' ) $(t).find('LI A').bind('click', function() { return false; });
}
// Loading message
$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
// Get the initial file list
showTree( $(this), escape(o.root) );
});
}
});
})(jQuery);
Following is the HTML
<script>
$(document).ready( function() {
$('.container_id').fileTree({ root: '/', script: 'jqueryFileTree.php', multiFolder: false }, function(file) {
//alert(file);
openFile(file);
});
function openFile(file){
alert(file);
}
});
If you're using jQuery File Tree, it looks like you could just pass a callback that loads the selected file in the right side.
Related
I use this Jquery code to hide the € symbol on my page.
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
but for some reason I'm unable to get it to work inside WordPress.
I know it has to be in the Document ready function because of the no-conflict mode.
So that is what I have done.
This code is in the same js file i use for other scripts loaded on the same page;
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
(function($){
jQuery(document).ready(function(){
console.log("ready to use!");
if(jQuery('.single-product').length > 0) {
var _sfm_brand = '';
var _sfm_model = '';
var _sfm_generation = '';
var _sfm_engine = '';
var _sfm_engine_ecu = '';
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
_sfm_brand = getUrlVars()["_sfm_brand"];
_sfm_model = getUrlVars()["_sfm_model"];
_sfm_generation = getUrlVars()["_sfm_generation"];
_sfm_engine = getUrlVars()["_sfm_engine"];
_sfm_engine_ecu = getUrlVars()["_sfm_engine_ecu"];
if(typeof _sfm_brand !== "undefined" && _sfm_brand != "") {
jQuery('input[name="tmcp_textfield_0"]').val(decodeURIComponent(_sfm_brand));
jQuery('input[name="tmcp_textfield_0"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_0"]').val('');
}
if(typeof _sfm_model !== "undefined" && _sfm_model != "") {
jQuery('input[name="tmcp_textfield_1"]').val(decodeURIComponent(_sfm_model));
jQuery('input[name="tmcp_textfield_1"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_1"]').val(decodeURIComponent(""));
}
if(typeof _sfm_generation !== "undefined" && _sfm_generation != "") {
jQuery('input[name="tmcp_textfield_2"]').val(decodeURIComponent(_sfm_generation));
jQuery('input[name="tmcp_textfield_2"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_2"]').val(decodeURIComponent(""));
}
if(typeof _sfm_engine !== "undefined" && _sfm_engine != "") {
jQuery('input[name="tmcp_textfield_3"]').val(decodeURIComponent(_sfm_engine));
jQuery('input[name="tmcp_textfield_3"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_3"]').val(decodeURIComponent(""));
}
if(typeof _sfm_engine_ecu !== "undefined" && _sfm_engine_ecu != "") {
jQuery('input[name="tmcp_textfield_4"]').val(decodeURIComponent(_sfm_engine_ecu));
jQuery('input[name="tmcp_textfield_4"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_4"]').val(decodeURIComponent(""));
}
}
});
})(jQuery);
And that code is working great. So I'm sure the file is loaded.
Also, what is strange is when loading the js file by the url I get it like this:
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
I also tried to change the € symbol with € and u20ac but they are also not working.
Any one who can help me out?
Thank you :)
EDIT: in Jsfiddle it is working. And I allready did some other articles, but with no luck. So that is why I'm posting my own.
Wordpress had alot of javascript and php functions loaded, so may one of theme overide or conflict with your codes.
If what you want is hide € character, better add this into your theme's functions.php:
function replace_text($text) {
$text = str_replace('€', '', $text);
return $text;
}
add_filter('the_content', 'replace_text');
in case above method not working. Use this instead:
jQuery(document).ready(function(){
jQuery('body').hover(function() {
let search = '€';
if(jQuery('.amount:contains('+search+')').html()!=undefined){
var text =
jQuery('.amount:contains('+search+')').html().replace(search, '');
jQuery('.amount:contains('+search+')').html(text);
}else{
return false;
}
});
});
I also did try to change the currency symbol with an function. But It is not getting the page-template;
add_filter( 'woocommerce_currency_symbol', 'change_currency_symbol', 10, 2 );
function change_currency_symbol( $symbols, $currency ) {
if ( is_page_template( 'archive-chiptuning.php' ) && ( 'EUR' === $currency )) {
return '';
}
return $symbols;
}
Without is_page_template it is working, but since I use different products, with different currencys (€ and credit(s)) I'm not able to use it like that. Because it changes all the symbols.
EDIT: check for page template outside loop:
add_filter( 'woocommerce_currency_symbol', 'change_currency_symbol', 10, 2 );
function change_currency_symbol( $symbols, $currency ) {
global $template;
if ( basename( $template ) === 'archive-chiptuning.php' && ( 'EUR' === $currency )) {
return '';
}
return $symbols;
}
Use:
global $template;
if ( basename( $template ) === 'archive-chiptuning.php'
Thanks to this post: https://wordpress.stackexchange.com/questions/328384/is-page-template-not-working/375028#375028
I installed an plugin on my current clean wordpress installation. However I always get the following error as soon as the widget for the plugin gets laoded
TypeError: $ is not a function
I checked the js files for the addon and they all seem to make proper use of jQuery instead of $ also the register_script function requires jquery as dependency
Below you can see the add_action function
if (!is_admin()) {
function woocommerce_ogonecw_add_frontend_css() {
wp_register_style('woocommerce_ogonecw_frontend_styles', plugins_url('resources/css/frontend.css', __FILE__));
wp_enqueue_style('woocommerce_ogonecw_frontend_styles');
true);
wp_register_script('ogonecw_frontend_script', plugins_url('resources/js/frontend.js', __FILE__), array(
'jquery'
));
wp_enqueue_script('ogonecw_frontend_script');
wp_localize_script('ogonecw_frontend_script', 'woocommerce_ogonecw_ajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'woocommerce_ogonecw_add_frontend_css');
frontend.js looks like this
jQuery(function (jQuery) {
var isSubmitted = false;
var CheckoutObject = {
cssClass: '',
successCallback: '',
placeOrder: function() {
var form = jQuery('form.checkout');
var form_data = form.data();
// WGM: Back Button
if(jQuery("input[name=cw-wgm-button-back]").length > 0) {
return true;
}
//WGM: MultiStep
if(jQuery("input[name=wc_gzdp_step_submit]").length > 0) {
if(jQuery("input[name=wc_gzdp_step_submit]").val() == "address"){
return true;
}
}
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
var secondRun = false;
if(jQuery("input[name=ogonecw_payment_method_choice]").length > 0) {
secondRun = true;
selectedPaymentMethodElement = jQuery("input[name=ogonecw_payment_method_choice]");
selectedPaymentMethod = selectedPaymentMethodElement.val();
}
var moduleName = 'ogonecw';
var selectedModuleName = (selectedPaymentMethod != undefined) ?
selectedPaymentMethod.toLowerCase().substring(0, moduleName.length) : '';
onOgoneCwCheckoutPlaceObject = this;
if (moduleName == selectedModuleName) {
form.addClass('processing');
if ( form_data["blockUI.isBlocked"] != 1 ) {
form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
this.successCallback = previewAuthorization;
this.cssClass = 'ogonecw-preview-fields';
onOgoneCwCheckoutPlaceObject = this;
if(secondRun) {
this.generateOrder(form, selectedPaymentMethod);
return false;
}
var validateFunctionName = 'cwValidateFields'+selectedPaymentMethod.toLowerCase();
var validateFunction = window[validateFunctionName];
if (typeof validateFunction != 'undefined') {
validateFunction(function(valid){onOgoneCwCheckoutPlaceObject.successCall();}, function(errors, valid){onOgoneCwCheckoutPlaceObject.failureCall(errors, valid);});
return false;
}
onOgoneCwCheckoutPlaceObject.successCall();
return false;
}
},
failureCall: function(errors, valid){
alert(errors[Object.keys(errors)[0]]);
var form = jQuery('form.checkout');
form.removeClass('processing').unblock();
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
},
successCall : function(){
var form = jQuery('form.checkout');
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
onOgoneCwCheckoutPlaceObject = this;
if(selectedPaymentMethodElement.parents('li').find('.ogonecw-validate').length > 0){
var ajaxUrl;
if(typeof wc_checkout_params != 'undefined') {
ajaxUrl = wc_checkout_params.ajax_url;
}
if(typeof checkoutUrl == 'undefined') {
ajaxUrl = woocommerce_params.ajax_url;
}
var separator = ajaxUrl.indexOf('?') !== -1 ? "&" : "?";
ajaxUrl = ajaxUrl+separator+"action=woocommerce_ogonecw_validate_payment_form";
var inputData = getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase());
var postData = "&";
jQuery.each(inputData, function(key, value) {
postData += encodeURIComponent(key)+"="+encodeURIComponent(value)+"&";
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: form.serialize()+postData+ onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
response = jQuery.parseJSON(code);
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch(err ){
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.message ) {
form.prepend(response.message);
} else {
form.prepend(code);
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
}
},
dataType: 'html'
});
return false;
}
else {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
},
generateOrder: function(form, selectedPaymentMethod) {
onOgoneCwCheckoutPlaceObject = this;
var checkoutUrl;
if(typeof wc_checkout_params != 'undefined') {
checkoutUrl = wc_checkout_params.checkout_url;
}
if(typeof checkoutUrl == 'undefined') {
checkoutUrl = woocommerce_params.checkout_url;
}
jQuery.ajax({
type: 'POST',
url: checkoutUrl,
data: form.serialize() + "&" + onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
if (code.indexOf("<!--WC_START-->") >= 0) {
code = code.split("<!--WC_START-->")[1];
}
if (code.indexOf("<!--WC_END-->") >= 0) {
code = code.split("<!--WC_END-->")[0];
}
try {
// Check for valid JSON
response = jQuery.parseJSON( code );
} catch ( e ) {
// Attempt to fix the malformed JSON
var validJson = code.match( /{"result.*"}/ );
if ( null === validJson ) {
throw 'Invalid response';
} else {
response = jQuery.parseJSON(validJson[0]);
}
}
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.successCallback(response, selectedPaymentMethod);
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch( err ) {
if ( response.reload === 'true' ) {
window.location.reload();
return;
}
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.messages ) {
form.prepend( response.messages );
} else {
form.prepend( code );
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
// Trigger update in case we need a fresh nonce
if ( response.refresh === 'true' ) {
jQuery( 'body' ).trigger( 'update_checkout' );
}
jQuery( 'body' ).trigger( 'checkout_error' );
}
},
dataType: 'html'
});
},
};
var getFormFieldValues = function(parentCssClass, paymentMethodPrefix) {
var output = {};
jQuery('.' + parentCssClass + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(paymentMethodPrefix, 0) === 0) {
name = name.substring(paymentMethodPrefix.length);
name = name.substring(1, name.length -1 );
if(this.type == "radio") {
if(this.checked) {
output[name] = jQuery(this).val();
}
}
else{
output[name] = jQuery(this).val();
}
}
});
return output;
};
var generateHiddenFields = function(data) {
var output = '';
jQuery.each(data, function(key, value) {
output += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
return output;
};
var removeNameAttributes= function(cssClass) {
// Remove name attribute to prevent submitting the data
jQuery('.' + cssClass + ' *[name]').each(function (element) {
jQuery(this).attr('data-field-name', jQuery(this).attr('name'));
if(jQuery(this).is(':radio')){
return true;
}
jQuery(this).removeAttr('name');
});
}
var addAlias = function(cssClass){
// Add listener for alias Transaction selector
jQuery('.' + cssClass).parents('li').find('.ogonecw-alias-input-box > select').bind('change', function() {
jQuery('body').trigger('update_checkout');
});
}
var registerCheckoutObject = function(){
bindOrderConfirmEvent(CheckoutObject);
};
var bindOrderConfirmEvent = function (CheckoutObject) {
var form = jQuery('form.checkout');
var attached = form.attr('data-ogonecw-attached');
if (attached != 'true') {
form.attr('data-ogonecw-attached', 'true');
form.bind('checkout_place_order', function() {
return CheckoutObject.placeOrder();
});
return false;
}
};
// We have to make sure that the JS in the response is executed.
jQuery( document ).ready(function() {
if (typeof window['force_js_execution_on_form_update_listener'] === 'undefined') {
window['force_js_execution_on_form_update_listener'] = true;
jQuery('body').bind('updated_checkout', function() {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
}
});
jQuery( document ).ajaxStop(function(event, xhr, settings) {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
var previewAuthorization = function (result, selectedPaymentMethod) {
if(typeof result.redirect !== 'undefined') {
var additionalFields = jQuery('<div class="ogonecw-preview-fields" style="display: none;"></div>');
jQuery('.' + 'ogonecw-preview-fields' + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(selectedPaymentMethod.toLowerCase(), 0) === 0) {
jQuery(additionalFields).append(jQuery(this));
}
});
var redirectUrl;
if ( result.redirect.indexOf( "https://" ) != -1 || result.redirect.indexOf( "http://" ) != -1 ) {
redirectUrl = result.redirect;
} else {
redirectUrl = decodeURI( result.redirect );
}
jQuery.get(redirectUrl, function(data){
var newBodyString = data.replace(/^[\S\s]*<body[^>]*?>/i, "").replace(/<\/body[\S\s]*jQuery/i, "");
var newBody = jQuery("<div></div>").html(newBodyString);
if(newBody.find('.wgm-go-back-button').length > 0){
jQuery('body').html(newBody.html());
jQuery('form.checkout').append(additionalFields);
jQuery('form.checkout').append('<input type="hidden" name="ogonecw_payment_method_choice" value="'+selectedPaymentMethod+'"/>');
jQuery('.wgm-go-back-button').on('click', function() {
jQuery('form.checkout').append('<input type="hidden" name="cw-wgm-button-back" value="back"/>');
});
jQuery('form.checkout').on('submit', function(){
return CheckoutObject.placeOrder();
});
jQuery("html, body").animate({
scrollTop: jQuery("form.checkout").offset().top - 100
}, 1e3);
}
else {
window.location = decodeURI( redirectUrl );
}
});
}
else if(typeof result.ajaxScriptUrl !== 'undefined'){
jQuery.getScript(result.ajaxScriptUrl, function() {
eval("var callbackFunction = " + result.submitCallbackFunction);
callbackFunction(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
});
}
else {
var newForm = '<form id="ogonecw_preview_form" action="' + result.form_action_url + '" method="POST">';
newForm += result.hidden_form_fields;
newForm += generateHiddenFields(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
newForm += '</form>';
jQuery('body').append(newForm);
jQuery('#ogonecw_preview_form').submit();
}
}
});
So what exactly is causing this error since the plugin seems to be setup correctly
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);
I have a table with 80 articles in it, I have a checkbox for each article.
I have code (AJAX, PHP) to activate / deactivate the articles in bulk while checkboxes are checked.
I am finding my ajax call takes 2+ seconds to activate / deactivate all 80 records, this seems slow, can you see a way to improve my code?
All help appreciated!
Here is my Jquery / Ajax:
$(document).on("click",".applybtn",function() {
// GET SELECTOR
var selector = $("#selector").attr("name");
// GET OPTIONS
var option = $("#control").val();
var option2 = $("#control2").val();
if($(".idcheck").is(":checked")) {
// GET CHECKBOXS
var val = [];
$(".idcheck:checked").each(function(i) {
val[i] = $(this).val();
});
if(selector === 'article' || selector === 'articlecats') {
$.ajax({
type: "POST",
url: "controllers/articlecontrol.php",
data: { id: val, option: option, option2: option2, selector: selector },
success: function(data){
if(option == 'delete' || option2 == 'delete') {
$(".idcheck:checked").each(function() {
$(this).closest("tr").remove();
})
}
if(option == 'activate' || option2 == 'activate' || option == 'deactivate' || option2 == 'deactivate') {
document.location.reload(true);
}
$('.successmessage').html(data).fadeIn("fast").fadeOut(3000);
if($('.select-all').is(':checked')) {
$('.select-all').prop('checked', false);
}
}
});
return false;
}
}
else {
$('.errormessage').html("<div class='error'>Please Make Your Selection<\/div>").fadeIn("fast").fadeOut(3000);
}
});
Here is my PHP:
if (isset($_POST['option']) || isset($_POST['option2'])) {
// MULTI ACTIVATE ARTICLE
if ($selector === 'article' && $option === 'activate' || $option2 === 'activate') {
$id = $id;
foreach($id as $val) {
$update = array('article_active' => '1');
$where = array('article_id' => $val);
$sql = $database->update('wcx_articles', $update, $where);
}
if ($sql) {
echo '<div class="success">Article(s) Activated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Activating the Article(s) with ID'.$id.'</div>';
}
}
// MULTI DEACTIVATE ARTICLE
if ($selector === 'article' && $option === 'deactivate' || $option2 === 'deactivate') {
$id = $id;
foreach($id as $val) {
$update = array('article_active' => '0');
$where = array('article_id' => $val);
$sql = $database->update('wcx_articles', $update, $where);
}
if ($sql) {
echo '<div class="success">Article(s) Deactivated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Deactivating the Article(s) with ID'.$id.'</div>';
}
}
}
I'm using a custom mysqli wrapper to make the calls to DB:
// UPDATE TABLE
public function update( $table, $variables = array(), $where = array(), $limit = '' ) {
$sql = "UPDATE ". $table ." SET ";
foreach( $variables as $field => $value ) {
$updates[] = "`$field` = '$value'";
}
$sql .= implode(', ', $updates);
foreach( $where as $field => $value ) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
if( !empty( $limit ) ) {
$sql .= ' LIMIT '. $limit;
}
$query = mysqli_query( $this->link, $sql );
if( mysqli_error( $this->link ) ) {
$this->log_db_errors( mysqli_error( $this->link ), $sql, 'Fatal' );
return false;
}
else {
return true;
}
}
It looks like you're performing a single SQL update query for each article you're updating. Consider changing your PHP script so that you perform a single update for multiple articles.
Instead of generating SQL like this:
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 123;
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 456;
UPDATE wcx_articles SET article_active = 1 WHERE article_id = 789;
Performing one single update would likely be more efficient:
UPDATE wcx_articles SET article_active = 1 WHERE article_id IN (123, 456, 789);
That would be a decent starting point for improving efficiency of your code.
UPDATED
PHP
// MULTI ACTIVATE ARTICLE
if ($selector === 'article' && $option === 'activate' || $option2 === 'activate') {
$id = $id;
$update = "1";
$where = implode(',',$id);
$sql = $database->articleADUpdate('wcx_articles', $update, $where);
if ($sql) {
echo '<div class="success">Article(s) Activated Successfully</div>';
}
else {
echo '<div class="error">There was a problem Activating the Article(s) with ID'.$id.'</div>';
}
}
public function articleADUpdate($table, $variables, $where) {
$sql = "UPDATE wcx_articles SET article_active =".$variables." WHERE article_id IN ($where)";
if( !empty( $limit ) ) {
$sql .= ' LIMIT '. $limit;
}
$query = mysqli_query( $this->link, $sql );
if( mysqli_error( $this->link ) ) {
$this->log_db_errors( mysqli_error( $this->link ), $sql, 'Fatal' );
return false;
}
else {
return true;
}
}
i'm using the FileTree jquery plugin from http://labs.abeautifulsite.net/projects/js/jquery/fileTree/demo/
i'm trying to fix one bug
i lost all day trying different thing but i'm a beginner at javascript and i had no luck
i modified the code a bit but the problem is the same even with the original code
to see the bug go to the link above
from the first example select "documents" then "excel docs" then "documents" again
the li element containing "excel docs" has the class "expanded" even if the parent "documents" is closed
how can i remove the class from all children when a parent is closed ?
this is my last version of the code
if(jQuery) (function($){
$.extend($.fn, {
fileTree: function(o, h, dire) {
// Defaults
if( !o ) var o = {};
if( o.root == undefined ) o.root = '/';
if( o.script == undefined ) o.script = 'jqueryFileTree.php';
if( o.folderEvent == undefined ) o.folderEvent = 'click';
if( o.expandSpeed == undefined ) o.expandSpeed= 500;
if( o.collapseSpeed == undefined ) o.collapseSpeed= 500;
if( o.expandEasing == undefined ) o.expandEasing = null;
if( o.collapseEasing == undefined ) o.collapseEasing = null;
if( o.multiFolder == undefined ) o.multiFolder = true;
if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';
if(o.expanded == undefined) o.expanded = '';
$(this).each( function() {
function showTree(c, t) {
$(c).addClass('wait');
$(".jqueryFileTree.start").remove();
$.post(o.script, { dir: t }, function(data) {
$(c).find('.start').html('');
$(c).removeClass('wait').append(data);
if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
bindTree(c);
if (o.expanded != null) {
$(c).find('.directory.collapsed').each(function (i, f) {
if ((o.expanded).match($(f).children().attr('rel'))) {
showTree($(f), escape($(f).children().attr('rel').match(/.*\//)));
$(f).removeClass('collapsed').addClass('expanded');
};
});
};
},"html");
};
function bindTree(t) {
$(t).find('LI A').bind(o.folderEvent, function() {
if( $(this).parent().hasClass('directory') ) {
if( $(this).parent().hasClass('collapsed') ) {
// Expand
dire($(this).attr('rel'));
if( !o.multiFolder ) {
$(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
$(this).parent().parent().find('LI.directory').removeClass('expanded').addClass('collapsed');
}
$(this).parent().find('UL').remove(); // cleanup
showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );
$(this).parent().removeClass('collapsed').addClass('expanded');
} else {
// Collapse
$(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
$(this).parent().removeClass('expanded').addClass('collapsed');
}
} else {
h($(this).attr('rel'));
}
return false;
});
if( o.folderEvent.toLowerCase != 'click' ) $(t).find('LI A').bind('click', function() { return false; });
}
$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
showTree( $(this), escape(o.root) );
});
}
});
})(jQuery);