Jquery Script Tag in Header - wordpress

I know this is a really basic question, so forgive me. I have a script that works in a jfiddle, but I want to put it in my header and I can't figure out how to call it with a script tag and event handler(?).
Here's the script:
var retrieveValue = function(ev){
var $this = $(this),
val = $this.data('value');
if (val) {
$this.val(val);
}
},
hideValue = function(ev){
var $this = $(this);
$this.data('value', $this.val());
$this.val($this.val().replace(/^\d{5}/, '*****'));
};
$('#field_a7afui').focus(retrieveValue);
$('#field_a7afui').blur(hideValue);
$('#form_hv3hcs').submit(function(ev){
ev.preventDefault();
retrieveValue.call($('#field_a7afui')[0], ev);
alert($('#field_a7afui').val());
hideValue.call($('#field_a7afui')[0], ev);
});
Can someone please tell me what I need to put at the beginning and end of this just to throw it in my Wordpress header and call it a day?
Here's my jfiddle: http://jsfiddle.net/d5KaJ/40/

If that's what you were asking for...
into a script tag like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
jQuery(function( $ ) {
// CODE HERE
} )();
</script>

Related

Disable Woocomerce register button after one click

Hello I would like to disable the woocommmerce register page button after one click to avoid multiple clicks.
I have searched the forums and found a bunch of solutions for custom forms and I've tried the following JS code but had no luck. I have a feeling I am setting the wrong selector because I cannot for the life of me figure out what the correct selector for the default register button is.
<script>
function disableButton() {
var btn = document.getElementById('woocommerce-register-nonce');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
I've also tried :
<script>
jQuery('woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit').live('click', function (e) {
var self = this;
$(this).attr("disabled", "disabled");
do_something();
setTimeout(function () {
$(self).removeAttr('disabled');
}, 10000);
});
</script>
Some guidance would be very much appreciated.
Update!
Based on Onboardmass's suggestion I have corrected the selector and got it partially working using jquery.
<script>
jQuery('.woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit').click(function(){
jQuery(this).attr("disabled", "disabled");
});
</script>
The button now gets disabled on click however the issue I'm facing now is that the form does not get submitted.
The issue you're facing is because the selector is incorrect. It should be .woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit.
For anyone else who may need this I was able to figure this one out by reading through the suggestions and other threads I found. Thank you Onboardmass & Martin for the guidance!
The time out function is required for the click to register.
<script>
$(document).ready(function () {
$(".woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$(".woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit").prop('disabled', true);
}
});
</script>

Works in JSFiddle not in browser and '$ is not a function

I have this little snippet of code that works great in JSFiddle and in a Chrome extension. On clicking "button" it blurs the ID "content".
var dimthis = $("#content")
var button = $("button")
button.on("click", () => {
dimthis.toggleClass("alt")
});
I've been through quite a few of the similar question that say to add $(document).ready(function(){
before and this });`
at the end giving this
$(document).ready(function(){
var dimthis = $("#content")
var button = $("button")
button.on("click", () => {
dimthis.toggleClass("alt")
});
});
That has worked for me before but not helping with this little ditty of code.
When I add the second set of code I get "$ is not a function error"
Thanks in advance for the help.
***** ANSWER (since I can't post answers for some reason) ******
This is a Wordpress site and Wordpress uses jQuery.noConflict();
So, in Wordpress, $ is undefined ergo the message "$ is not a function error"
Instead of
$(document).ready(function(){
in Wordpress you need to use
jQuery(document).ready(function($) {
What worked is putting it in the child-themes funtion.php like this:
function load_dimmer_script(){
?>
<script>
jQuery(document).ready(function($) {
var dimthis = $("#content")
var button = $("button")
button.on("click", () => {
dimthis.toggleClass("alt")
});
});
</script>
<?php
}
add_action( 'wp_footer', 'load_dimmer_script' );
What this does is this: If the menu toggle is defined as a button, when the menu is clicked the content of the page (#content) gets blurred. Click menu toggle again, it goes unblurred.
See nova-energy.net
Here's the one piece of CSS needed:
#content.alt {
filter: blur(4px) !important;
}
You have to wrap the JS code:
jQuery(document).ready(function($) {
// your code
)};

Casperjs sendKeys not working

I have this code to fill an input, I can get input attributes yet I can't set the value, could anybody help me either if it's with other library please.
var casper = require('casper').create();
casper.start();
casper
.then(function(){
console.log("Start:");
})
.thenOpen("https://alsea.interfactura.com/RegistroDocumento.aspx?opc=Starbucks")
.then(function(){
casper.sendKeys('#ctl00_Main_RegistroClienteTicket1_txtTienda', '12345');
this.echo(this.getElementAttribute('input[type="text"][id="ctl00_Main_RegistroClienteTicket1_txtTienda"]', 'value'));
});
casper.run();
The sendKeys() work in your case. If you do a screenshot you see that the form element is filled with the value you set:
var casper = require('casper').create();
casper.start("https://alsea.interfactura.com/RegistroDocumento.aspx?opc=Starbucks");
casper.then(function() {
casper.sendKeys('#ctl00_Main_RegistroClienteTicket1_txtTienda', '12345');
});
casper.then(function() {
casper.capture("test.png");
this.echo(this.getElementAttribute('input[type="text"][id="ctl00_Main_RegistroClienteTicket1_txtTienda"]', 'value'));
});
casper.run();
Probably the value is set is saved somewhere else on this site.

javascript window.print after loading multiple google map through php loop

I am successful to display multiple maps through a php loop. But at the end I am calling window.print. My problem is that the window.print is getting triggered before the map loads and blank space is shown on the print page.
Here is my example code:
{loop starts}
<div latitude="<?php echo $row['lat'];?>" longitude="<?php echo $row['lng'];?>" zoom="<?php echo $row['map_zoom_level'];?>" class="map_canvas"></div>
{loop ends}
Javascript:
$(document).ready(function(){
$('.map_canvas').each(function(index, Element) {
var lat = $(Element).attr('latitude');
var lng = $(Element).attr('longitude');
var latlng = lat+','+lng;
var zoomlevel = parseInt($(Element).attr('zoom'));
var origin = new google.maps.LatLng(lat,lng)
$(Element).gmap({'zoom': zoomlevel}).bind('init', function(ev, map) {
$(Element).gmap('get','map').setOptions({'center':origin});
$(Element).gmap('addMarker', {'position': latlng}).click();
});
});
window.print();
});
Can anyone help me fix this.

How to determine if CSS has been loaded?

How can i Assert that the CSS for a page has successfully loaded and applied its styles in Watin 2.1?
After doing some research and writing up my answer, I stumbled upon this link that explains everything you need to know about CSS, when it is loaded and how you can check for it.
The link provided explains it so well, in fact, that I'm adding some quotes from it for future reference.
If you're curious, my answer was going to be #2 and a variation of #4.
When is a stylesheet really loaded?
...
With that out of the way, let's see what we have here.
// my callback function
// which relies on CSS being loaded function
CSSDone() {
alert('zOMG, CSS is done');
};
// load me some stylesheet
var url = "http://tools.w3clubs.com/pagr/1.sleep-1.css",
head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
// MAGIC
// call CSSDone() when CSS arrives
head.appendChild(link);
Options for the magic part, sorted from nice-and-easy to ridiculous
listen to link.onload
listen to link.addEventListener('load')
listen to link.onreadystatechange
setTimeout and check for changes in document.styleSheets
setTimeout and check for changes in the styling of a specific element you create but style with the new CSS
5th option is too crazy and assumes you have control over the content of the CSS, so forget it. Plus it checks for current styles in a timeout meaning it will flush the reflow queue and can be potentially slow. The slower the CSS to arrive, the more reflows. So, really, forget it.
So how about implementing the magic?
// MAGIC
// #1
link.onload = function () {
CSSDone('onload listener');
};
// #2
if (link.addEventListener) {
link.addEventListener('load', function() {
CSSDone("DOM's load event");
}, false);
};
// #3
link.onreadystatechange = function() {
var state = link.readyState;
if (state === 'loaded' || state === 'complete') {
link.onreadystatechange = null;
CSSDone("onreadystatechange");
}
};
// #4
var cssnum = document.styleSheets.length;
var ti = setInterval(function() {
if (document.styleSheets.length > cssnum) {
// needs more work when you load a bunch of CSS files quickly
// e.g. loop from cssnum to the new length, looking
// for the document.styleSheets[n].href === url
// ...
// FF changes the length prematurely :(
CSSDone('listening to styleSheets.length change');
clearInterval(ti);
}
}, 10);
// MAGIC ends
There has been an update to the article lined to by #ShadowScripter. The new method purportedly works in all browsers, including FF.
var style = document.createElement('style');
style.textContent = '#import "' + url + '"';
var fi = setInterval(function() {
try {
style.sheet.cssRules; // <--- MAGIC: only populated when file is loaded
CSSDone('listening to #import-ed cssRules');
clearInterval(fi);
} catch (e){}
}, 10);
document.getElementsByTagName('head')[0].appendChild(style);
After page load you can verify the style on some of your elements something like this:
var style = browser.Div(Find.ByClass("class")).Style;
Assert.That(Style.Display, Is.StringContaining("none"));
Assert.That(Style.FontSize, Is.EqualTo("10px"));
And etc...
Since browser compatibility can vary, and new future browser standards subject to change, I would recommend a combination of the onload listener and adding CSS to the style sheet so you can listen for when the HTML elements z-index changes if you are using a single style sheet. Otherwise, use the function below with a new meta tag for each style.
Add the following to the CSS file that you are loading:
#*(insert a unique id for he current link tag)* {
z-index: 0
}
Add the following to your script:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
Example
index.html:
<!doctype html>
<html>
<head>
<link rel=stylesheet id="EpicStyleID" href="the_style.css" />
<script async href="script.js"></script>
</head>
<body>
CSS Loaded: <span id=result>no</span>
</body>
</html>
script.js:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
/*************************************/
whencsslinkloads(
document.getElementById('EpicStyleID'),
function(){
document.getElementById('result').innerHTML = '<font color=green></font>'
}
)
the_style.css
#EpicStyleID {
z-index: 0
}
PLEASE do not make your script load synchronously (without the async attribute) just so you can capture the link's onload event. There are better ways, like the method above.

Resources