I'm trying to send a variable to the server, using XMLHttpRequest.
I tested it on local on a non-Wordpress file and it works. But on production, on my Wordpress file, the onreadystatechange AJAX status doesn't get to 200.
Is there anything I need to be aware when XMLHttpRequesting in Wordpress?
I have the following code for sending data to the server using XMLHTTP Request but it's not working I don't know why? I'm getting the following error:
VM704:1 POST http://localhost/amt/wp-admin/admin-ajax.php 400 (Bad Request)
here is my WordPress code:
add_action('wp_ajax_csv_file', 'csv_file');
add_action('wp_ajax_nopriv_csv_file', 'csv_file');
function csv_file()
{
if($_POST['rtype'] == 'enr_data'){
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
for ($i = 0; $i < 10; $i++) {
//Hard work!!
sleep(1);
$p = ($i + 1) * 10; //Progress
$response = array('message' => $p . '% complete. server time: ' . date("h:i:s", time()),
'progress' => $p);
echo json_encode($response);
}
sleep(1);
$response = array('message' => 'Complete',
'progress' => 100);
echo json_encode($response);
die();
}
}
function ajax_stream() {
if (!window.XMLHttpRequest) {
alert("Your browser does not support the native XMLHttpRequest object.");
return;
}
try {
var xhr = new XMLHttpRequest();
xhr.previous_text = '';
xhr.responseType = "text";
xhr.onerror = function() {
alert("[XHR] Fatal Error.");
};
xhr.onreadystatechange = function() {
try {
if (xhr.readyState == 4) {
alert('[XHR] Done')
} else if (xhr.readyState > 2) {
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse(new_response);
document.getElementById("divProgress").innerHTML += result.message + '<br />';
document.getElementById('progressor').style.width = result.progress + "%";
xhr.previous_text = xhr.responseText;
}
} catch (e) {
alert("[XHR STATECHANGE] Exception: " + e);
}
};
var data = "action=csv_file&rtype=enr_data";
xhr.open("POST", ajaxurl, true);
xhr.send(data);
console.log(xhr);
} catch (e) {
alert("[XHR REQUEST] Exception: " + e);
}
}
#divProgress {
border: 2px solid #ddd;
padding: 10px;
width: 300px;
height: 265px;
margin-top: 10px;
overflow: auto;
background: #f5f5f5;
}
#progress_wrapper {
border: 2px solid #ddd;
width: 321px;
height: 20px;
overflow: auto;
background: #f5f5f5;
margin-top: 10px;
}
#progressor {
background: #07c;
width: 0%;
height: 100%;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}
.demo_container {
width: 680px;
margin: 0 auto;
padding: 30px;
background: #FFF;
margin-top: 50px;
}
.my-btn,
.my-btn2 {
width: 297px;
margin-top: 22px;
float: none;
display: block;
}
h1 {
font-size: 22px;
margin-bottom: 20px;
}
.float_left {
float: left;
}
.float_right {
float: right;
}
.demo_container::after {
content: "";
clear: both;
display: block;
}
.ghost-btn.active {
border: 2px solid #D23725;
color: #D23725;
}
.ghost-btn {
display: inline-block;
text-decoration: none;
border: 2px solid #3b8dbd;
line-height: 15px;
color: #3b8dbd;
-webkit-border-radius: 3px;
-webkit-background-clip: padding-box;
-moz-border-radius: 3px;
-moz-background-clip: padding;
border-radius: 3px;
background-clip: padding-box;
font-size: 15px;
padding: .6em 1.5em;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
-o-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
background: #ffffff;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
cursor: pointer;
zoom: 1;
-webkit-backface-visibility: hidden;
position: relative;
margin-right: 10px;
}
.ghost-btn:hover {
-webkit-transition: 0.2s ease;
-moz-transition: 0.2s ease;
-o-transition: 0.2s ease;
transition: 0.2s ease;
background-color: #3b8dbd;
color: #ffffff;
}
.ghost-btn:focus {
outline: none;
}
.ghost-btn.active {
border: 2px solid #D23725;
color: #D23725;
}
.ghost-btn.active:hover {
border: 2px solid #D23725;
background: #FFF;
}
.method_wrappers {
margin-bottom: 20px;
}
<div class="demo_container">
<div class='method_wrappers'>
<a class='ghost-btn active' href='#'>XHR Method</a>
<a class='ghost-btn' href='../example2/index.html'>Iframe Method</a>
</div>
<h1>AJAX progress bar for PHP script without polling (XHR method)</h1>
<div class='float_left'>
<h3>Progress Bar</h3>
<div id='progress_wrapper'>
<div id="progressor"></div>
</div>
<a onclick="ajax_stream();" class='my-btn'>Start Ajax Streaming</a>
</div>
<div class='float_right'>
<h3>Log</h3>
<div id="divProgress"></div>
</div>
</div>
When using an XHR instead of a jQuery/AJAX request, I found it's actually easier and more reliable to append the action to the ajaxurl.
var xhr = new XMLHttpRequest();
var url = ajaxurl + '?action=csv_file';
xhr.open( 'POST', url, true );
The method of passing data to the request varies a bit, but 95% of the time I use a simple object to query string function:
// Convert an Object into a Query String
function objectToQueryString(obj){
return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
}
Which in practice will turn a simple data object
var data = {
'post_id': ajax_object.post_id,
'rtype': 'enr_data',
'field': element.getAttribute('data-field'),
};
into a simple query string:
post_id=1234&rtype=enr_data&field=bar
This lets me pass the data off as a string posted to the target function:
var dataString = objectToQueryString( data );
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(dataString);
For larger or more complex tasks you can actually effectively wrap the whole thing in a Promise as well, which I'll do if for instance I need to upload a handful of files and pass those along one by one for resizing.
The right solution would be to use "encodeURIComponent". Which correctly transcodes all strings and characters. The function will be:
function encodeURI(obj) {
var result = '';
var splitter = '';
if (typeof obj === 'object') {
Object.keys(obj).forEach(function (key) {
result += splitter + key + '=' + encodeURIComponent(obj[key]);
splitter = '&';
});
}
return result;
},
End then use it in your request:
var data = {
action: 'your action',
data: JSON.stringify(data)
};
let request = new XMLHttpRequest();
request.open('POST', '/wp-admin/admin-ajax.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(encodeURI(data));
Related
I have a function that turns an array into modal window links as a template literal.
The code that creates the links works fine outside of the function
But once it gets rendered in the function it no longer works. I can't find any errors, but it does NOT work.
However, if I copy the HTML that the function renders and save that as actual HTML, that works fine on its own.
A good chunk of the JavaScript portion of the code is posted below. A full version is on Codepen.
There are two sections in the example on Codepen:
The first section has the code as it's rendered by the function.
The second section is copied from the Elements tab in Developer Tools and saved as actual HTML.
"use strict";
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
let modal = e.currentTarget;
if (modal.dataset.target) {
let modalID = modal.dataset.target;
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
let modalLink = "";
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>
`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
My apologies in advance for it not being stripped down to just the bare minimum. But in order to replicate the problem, it required more code than it probably should have had. I've been reworking this for the better part of a day without any insight as to what the real problem is. I've been creating functions using template literals just like this for years now, usually with a high success rate. Whatever the problem is, I need to know so I can get past it. The only anomaly that I spotted is that–in the version on Codepen–the only thing that doesn't work in that version is once the modal is displayed clicking on the background does not dismiss the modal like it does elsewhere. If that's significant as to what the problem may be, I'm not sure what the connection is.
Usually when I take the time to painstakingly write everything out like this I typically either spot the problem or figure out an alternative solution so there's no need to actually post a question, but this does not appear to be one of those times. As always, your help is very much appreciated!
The issue appears to just be timing. Your code is executed in order, and the first part gets all of the modal buttons on the page and sets the appropriate event listeners. Then the second part of your code adds 2 modal buttons, which were not present earlier.
By simply wrapping the first part of your code in a function and calling it later (or swapping the order of those two parts of code), everything works as expected.
"use strict";
const _InitModal = () => {
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
let modal = e.currentTarget;
console.log("modal = " + modal);
if (modal.dataset.target) {
let modalID = modal.dataset.target;
console.log("modal.dataset.target = " + modal.dataset.target);
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
console.log(`modal.dataset.header = ${modal.dataset.header}`);
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
// e.preventDefault();
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
console.log("e=" + e);
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
}
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
let modalLink = "";
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
_InitModal();
.modal-background {
font-family: sans-serif;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: none;
overflow: auto;
background-color: rgba(0, 0, 0, 0.9);
z-index: 9999;
background: rgba(55, 55, 55, 0.6);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.modal-window {
position: relative;
background-color: #ffffff;
width: 50%;
margin: 10% auto;
border-radius: 0.5rem;
padding: 0.75rem;
border: 1px groove #ccc;
/* box-shadow: 1px 1px 1px #999, 2px 2px 2px #000; */
}
.close-modal:hover,
.close-modal:focus {
color: rgba(255, 255, 255, 1);
cursor: pointer;
background: red;
transition: 1s;
text-shadow: 1px 1px 1px #999, 2px 2px 2px #000;
}
button.close-modal {
position: absolute;
top: -0.75rem;
right: -0.75rem;
padding: 0.05rem 0.75rem;
background: #999;
color: #ccc;
border-radius: 50%;
border: none;
outline: none;
-webkit-transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
-webkit-animation-name: animatebottom;
-webkit-animation-duration: 1.5s;
animation-name: animatebottom;
animation-duration: 1.5s;
}
button.close-modal::before {
content: "\D7";
font-size: 2rem;
}
.modal-window {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.5s;
animation-name: animatetop;
animation-duration: 0.5s;
}
.modal-header {
height: 30px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-header h1 {
font-size: 1.1rem;
}
.modal-footer {
height: 20px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-content {
background-color: #fff;
height: calc(100% - 70px);
border-radius: 0.5rem;
border: 0.1rem groove #ddd;
overflow: hidden;
}
.button-footer {
background: #fff;
border-radius: 0.5rem;
border: 1px outset #aaa;
padding: 0.2rem;
color: #999;
transition: 1s;
cursor: pointer;
}
.button-footer:hover {
background: #fdfdfd;
color: #555;
border: 1px inset #ddd;
text-shadow: 0.05rem 0.05rem 0.05rem #ccc, 0.055rem 0.055rem 0.055rem #999,
0.06rem 0.06rem 0.06rem #333;
transition: 1s;
}
.close-btn:hover {
color: white;
background: #f00;
cursor: pointer;
}
#modal_iframe {
width: 100%;
height: 100%;
}
button.modal-button {
border-radius: 0.5rem;
border: 0px solid #aaa;
padding: 0;
cursor: pointer;
}
.modal-button-img {
border-radius: 0.5rem;
border: 0.1rem groove #444;
cursor: pointer;
}
.sepia:hover {
filter: sepia(150%);
}
/*
.none {
display: none;
}
*/
#-webkit-keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#-webkit-keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
#keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
.container {
border-radius: 0.5rem;
border: 1px solid #aaa;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
font-family: sans-serif;
}
main,
aside {
font-family: sans-serif;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
}
h2 {
text-align: center;
font-family: sans-serif;
font-weight: normal;
font-size: 1.2rem;
}
span {
font-size: 75%;
background: #ffff0055;
}
<div id="modal_window" class="modal-background">
<div class="modal-window">
<button class="close-modal" data-dismiss="modal"></button>
<div class="modal-header"></div>
<div class="modal-content">
<iframe src="#" id="modal_iframe" frameborder="0">If you'd have had a real browser, I wouldn't be boring you with this now...</iframe>
</div>
<div class="modal-footer"><button class="button-footer">Open In New Tab</button></div>
</div>
</div>
<div class="container">
<h2><code>main</code> Content Rendered By JavaScript</h2>
<main>
Main
</main>
<span>working now</span>
</div>
EDIT: UPDATED jsfiddle (https://jsfiddle.net/3ow12Lk0/2/)
https://jsfiddle.net/gb8qsrzc/
Im trying to pass variables to pbModal.open
buttonAmount, amountType, toAddress, successField, successMsg, successCallback, bchAmount
(towards bottom of JS), then to function buildOut:
function buildOut(buttonAmount, amountType, toAddress, successField, successMsg, successCallback, bchAmount) {}
in order to display "results" in modal with
// Create content area and append to modal
resultHolder = document.createElement("div");
resultHolder.className = "paybutton-content";
resultHolder.id = "result";
resultHolder.innerHTML = (buttonAmount + " " + amountType + " = " + bchAmount/100000000 + " BCH");
this.modal.appendChild(resultHolder);
Being new, I dont know what to call this.
Attempting to get anything to work, I attempted to just pass all variables anywhere and Im not sure Im even close to doing this correctly.
The code I am working on is here: https://jsfiddle.net/gb8qsrzc/
And the modal original is here for reference https://jsfiddle.net/theranjitkumar/1yhthrv8/
how should I be passing variables from buttons to the modal?
EDIT: UPDATED jsfiddle (https://jsfiddle.net/3ow12Lk0/2/)
I think the issue is related to the fact that you are not passing the parameters in the constructor of the modal. i.e. :
var pbModal = new Modal({
content: pbContent,
buttonAmount: buttonAmount,
amountType: amountType,
toAddress: toAddress,
successField: successField,
successMsg: successMsg,
successCallback: successCallback,
bchAmount: bchAmount
});
pbModal.open();
You can try the code above as illustrated in the sample below.
Also, you may want to have another look at the rate/conversion calculations... they seemed incorrect to me but I am not sure what the right formula should be so I didn't try to fix that :)
// Create an immediately invoked functional expression to wrap our code
(function() {
// Define our constructor
this.Modal = function(buttonAmount, amountType, toAddress, successField, successMsg, successCallback, bchAmount) {
// Create global element references
this.closeButton = null;
this.modal = null;
this.overlay = null;
// Determine proper prefix
this.transitionEnd = transitionSelect();
// Define option defaults
var defaults = {
autoOpen: false,
className: 'fade-and-drop',
closeButton: false,
content: "",
maxWidth: 270,
minWidth: 250,
overlay: true
}
// Create options by extending defaults with the passed in arugments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = extendDefaults(defaults, arguments[0]);
}
if (this.options.autoOpen === true){
this.open();
}
}
// Public Methods
Modal.prototype.close = function() {
var _ = this;
this.modal.className = this.modal.className.replace(" paybutton-open", "");
this.overlay.className = this.overlay.className.replace(" paybutton-open",
"");
this.modal.addEventListener(this.transitionEnd, function() {
_.modal.parentNode.removeChild(_.modal);
});
this.overlay.addEventListener(this.transitionEnd, function() {
if (_.overlay.parentNode) _.overlay.parentNode.removeChild(_.overlay);
});
}
Modal.prototype.open = function() {
buildOut.call(this);
initializeEvents.call(this);
window.getComputedStyle(this.modal).height;
this.modal.className = this.modal.className +
(this.modal.offsetHeight > window.innerHeight ?
" paybutton-open paybutton-anchored" : " paybutton-open");
this.overlay.className = this.overlay.className + " paybutton-open";
}
// Private Methods
function buildOut(buttonAmount, amountType, toAddress, successField, successMsg, successCallback, bchAmount) {
var content, contentHolder, docFrag, resultHolder, buttonAmount, amountType, toAddress, successField, successMsg, successCallback, bchAmount;
/*
* If content is an HTML string, append the HTML string.
* If content is a domNode, append its content.
*/
if (typeof this.options.content === "string") {
content = this.options.content;
} else {
content = this.options.content.innerHTML;
}
// Create a DocumentFragment to build with
docFrag = document.createDocumentFragment();
// Create modal element
this.modal = document.createElement("div");
this.modal.className = "paybutton-modal " + this.options.className;
this.modal.style.minWidth = this.options.minWidth + "px";
this.modal.style.maxWidth = this.options.maxWidth + "px";
// If closeButton option is true, add a close button
if (this.options.closeButton === true) {
this.closeButton = document.createElement("button");
this.closeButton.className = "paybutton-close close-button";
this.closeButton.innerHTML = "×";
this.modal.appendChild(this.closeButton);
}
// If overlay is true, add one
if (this.options.overlay === true) {
this.overlay = document.createElement("div");
this.overlay.className = "paybutton-overlay " + this.options.className;
docFrag.appendChild(this.overlay);
}
// Create content area and append to modal
contentHolder = document.createElement("div");
contentHolder.className = "paybutton-content";
contentHolder.innerHTML = content;
this.modal.appendChild(contentHolder);
// Create content area and append to modal
resultHolder = document.createElement("div");
resultHolder.className = "paybutton-content";
resultHolder.id = "result";
resultHolder.innerHTML = (this.options.buttonAmount + " " + this.options.amountType + " = " + this.options.bchAmount / 100000000 + " BCH");
this.modal.appendChild(resultHolder);
// Append modal to DocumentFragment
docFrag.appendChild(this.modal);
// Append DocumentFragment to body
document.body.appendChild(docFrag);
}
function extendDefaults(source, properties) {
var property;
for (property in properties) {
if (properties.hasOwnProperty(property)) {
source[property] = properties[property];
}
}
return source;
}
function initializeEvents() {
if (this.closeButton) {
this.closeButton.addEventListener('click', this.close.bind(this));
}
if (this.overlay) {
this.overlay.addEventListener('click', this.close.bind(this));
}
}
function transitionSelect() {
var el = document.createElement("div");
if (el.style.WebkitTransition) return "webkitTransitionEnd";
if (el.style.OTransition) return "oTransitionEnd";
return 'transitionend';
}
var payButton = document.getElementsByClassName("pay-button");
for (var i = 0; i < payButton.length; i++) {
var payButtons = payButton[i];
// pull in attribute info from button when clicked
payButtons.addEventListener("click", function(event) {
var buttonAmount = this.getAttribute("amount");
var amountType = this.getAttribute("amount-type");
var toAddress = this.getAttribute("address");
var successField = this.getAttribute("success-field");
var successMsg = this.getAttribute("success-msg");
var successCallback = this.getAttribute("data-success-callback");
var bchAmount;
var test = "test message";
// check if amount type is set to bch or fiat
if (amountType === "BCH") {
bchAmount = 100000000 * buttonAmount;
} else if (amountType === "Satoshi") {
bchAmount = buttonAmount;
}
var qr = new QRious({
element: document.getElementById('qr'),
value: toAddress + "?amount=" + bchAmount,
background: 'white', // background color
foreground: 'black', // foreground color
backgroundAlpha: 1,
foregroundAlpha: 1,
level: 'M',
mime: 'image/png',
size: 250,
padding: null
});
var qrdecoded = qr.toDataURL();
var pbContent =
'<div>' + '<div>' +'<div>' +
'<div><img src="' + qrdecoded + '"></div>' +
'</div>' +
'<div>' +
'<div class="addressdiv"><span>Click QR code to Copy Address</span></div>' +
'</div>' +
'<div>' +
'<div class="amountdiv"><span>Amount = ' + bchAmount + ' BCH</span></div>' +
'</div>' +
'<div>' +
'<div><button class="pbmodal-button"><span>Open in BitcoinCash Wallet</span></button>' +
'</div>' +
'<div>' +
'<div><button class="pbmodal-button"><span>Send BCH with Badger Wallet</span></button></div>' +
'</div>' +
'<div>' +
'<div><button class="pbmodal-button"><span>Send BCH with Telecope Wallet</span></button></div>' +
'</div>' +
'<div>' +
'<div id = "result"></div>' +
'</div>' +
'</div>' +
'</div>';
var pbModal = new Modal({
content: pbContent,
buttonAmount: buttonAmount,
amountType: amountType,
toAddress: toAddress,
successField: successField,
successMsg: successMsg,
successCallback: successCallback,
bchAmount: bchAmount
});
pbModal.open();
});
}
}());
body {
font-family: Helvetica, Arial, san-serif;
font-size: 16px;
margin: 0;
padding: 0;
}
.pay-button {
border-radius: 4px;
cursor: pointer;
border: 2px solid orangeRed;
background: transparent;
position: relative;
padding: 0px;
min-width: 150px;
margin: 5px;
color: #fff;
/*For IE*/
}
.pay-button>span {
display: inline-block;
padding: 8px 16px;
background: linear-gradient(45deg, #fff 50%, orangeRed 50%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.pay-button:after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(45deg, orangeRed 50%, transparent 50%);
z-index: -1;
}
.pay-button>span,
.pay-button:after {
background-size: 300%;
background-position: 100%;
transition: .6s, font-size 0.2s;
}
.pay-button:hover>span,
.pay-button:hover:after {
background-position: 0;
font-size: 1.1em;
color: orangeRed;
/*For IE*/
}
.pbmodal-button {
border-radius: 4px;
cursor: pointer;
border: 2px solid orangeRed;
background: transparent;
position: relative;
padding: 0px;
width: 240px;
margin: 0px 0px 10px 0px;
color: #fff;
/*For IE*/
}
.pbmodal-button>span {
display: inline-block;
padding: 8px 16px;
background: linear-gradient(45deg, #fff 50%, orangeRed 50%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.pbmodal-button:after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(45deg, orangeRed 50%, transparent 50%);
z-index: -1;
}
.pbmodal-button>span,
.pbmodal-button:after {
background-size: 300%;
background-position: 100%;
transition: .6s, font-size .2s;
}
.pbmodal-button:hover>span,
.pbmodal-button:hover:after {
background-position: 0;
font-size: 1.08em;
color: orangeRed;
/*For IE*/
}
/* Modal Base CSS */
.paybutton-overlay {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
opacity: 0;
width: 100%;
height: 100%;
-webkit-transition: 1ms opacity ease;
-moz-transition: 1ms opacity ease;
-ms-transition: 1ms opacity ease;
-o-transition: 1ms opacity ease;
transition: 1ms opacity ease;
background: rgba(0, 0, 0, .6);
}
.addressdiv {
word-wrap: break-word;
font-size: 14px;
margin: 0px 0px 10px 0px;
}
.amountdiv {
word-wrap: break-word;
font-size: 16px;
margin: 0px 0px 10px 0px;
}
.paybutton-modal {
position: absolute;
z-index: 9999;
top: 50%;
left: 50%;
text-align: center;
opacity: 0;
overflow: auto;
width: 100%;
padding: 10px 10px 15px 10px;
/*padding: 24px 20px;*/
-webkit-transition: 1ms opacity ease;
-moz-transition: 1ms opacity ease;
-ms-transition: 1ms opacity ease;
-o-transition: 1ms opacity ease;
transition: 1ms opacity ease;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
border-radius: 5px;
background: #fff;
}
.paybutton-modal.paybutton-open.paybutton-anchored {
top: 20px;
-webkit-transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
-o-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
.paybutton-modal.paybutton-open {
opacity: 1;
}
.paybutton-overlay.paybutton-open {
opacity: 1;
}
/* Default Animation */
.paybutton-overlay.fade-and-drop {
display: block;
opacity: 0;
}
.paybutton-modal.fade-and-drop {
top: -300%;
opacity: 1;
display: block;
}
.paybutton-modal.fade-and-drop.paybutton-open {
top: 50%;
-webkit-transition: 300ms top 300ms ease;
-moz-transition: 300ms top 300ms ease;
-ms-transition: 300ms top 300ms ease;
-o-transition: 300ms top 300ms ease;
transition: 300ms top 300ms ease;
}
.paybutton-modal.fade-and-drop.paybutton-open.paybutton-anchored {
-webkit-transition: 300ms top 300ms ease;
-moz-transition: 300ms top 300ms ease;
-ms-transition: 300ms top 300ms ease;
-o-transition: 300ms top 300ms ease;
transition: 300ms top 300ms ease;
}
.paybutton-overlay.fade-and-drop.paybutton-open {
top: 0;
-webkit-transition: 300ms opacity ease;
-moz-transition: 300ms opacity ease;
-ms-transition: 300ms opacity ease;
-o-transition: 300ms opacity ease;
transition: 300ms opacity ease;
opacity: 1;
}
.paybutton-modal.fade-and-drop {
-webkit-transition: 300ms top ease;
-moz-transition: 300ms top ease;
-ms-transition: 300ms top ease;
-o-transition: 300ms top ease;
transition: 300ms top ease;
}
.paybutton-overlay.fade-and-drop {
-webkit-transition: 300ms opacity 300ms ease;
-moz-transition: 300ms opacity 300ms ease;
-ms-transition: 300ms opacity 300ms ease;
-o-transition: 300ms opacity 300ms ease;
transition: 300ms opacity 300ms ease;
}
/* Close Button */
.paybutton-close {
font-family: Helvetica, Arial, sans-serif;
font-size: 24px;
font-weight: 700;
line-height: 12px;
position: absolute;
top: 5px;
right: 5px;
padding: 5px 7px 7px;
cursor: pointer;
color: #fff;
border: 0;
outline: none;
background: #e74c3c;
}
.paybutton-close:hover {
background: #c0392b;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
<button class="pay-button" amount="0.038" amount-type="BCH" address="bitcoincash:qpajl5cvn0fjsqs30xppuxs3uuhzfdj4ncrcfdukt3" success-field="success" success-msg="Thank you for donating!">
<span>0.038 BCH</span>
</button>
<button class="pay-button" amount="0.1" amount-type="BCH" address="bitcoincash:qpajl5cvn0fjsqs30xppuxs3uuhzfdj4ncrcfdukt3" success-field="success" success-msg="Thank you for donating!">
<span>0.1 BCH</span>
</button>
<button class="pay-button" amount="10000" amount-type="Satoshi" address="bitcoincash:qpajl5cvn0fjsqs30xppuxs3uuhzfdj4ncrcfdukt3" success-field="success" success-msg="Thank you for donating!">
<span>10,000 Satoshi</span>
</button>
UPDATED
I added a second version that improves on the need to generate the code for all elements in the modal (divs, buttons, etc) every single time the buttons are clicked.
Instead, we can have a hidden div and its contents are updated on button click and adding/removing a class that hides/shows it as needed.
For OP: I worked on re-using this div but did not pay attention to the transition effects on the existing code.
A few minor tweaks are still needed for opacity and modal size, etc but I ran out of time to continue working on this part :)
UPDATE 2
Removed second approach as OP will not find it as useful (different requirements than I had anticipated)
I tried to search for tutorials on this effect. The effect that I wanted is an active underline (or border-bottom) under a link. When I click on a link, the underline will slide over to the next link and so on... One example is this question.
I know that what I have in html are buttons, not nav menu. So the coding would be different. I'm thinking that I might need to convert the buttons to nav menu if it doesn't work out.
Anyway, the problem is that I did try to use the example mentioned above to make the underline move to a clinked link. But it's not working...
Here's my code which is on codepen.
$(document).ready(function() {
$(".con-button").click(function(){
if(this.id == "c-all") {
$(".con-button").removeClass("active");
$("#c-all").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$(".con-button").removeClass("active");
$("#c-online").addClass("active");
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$(".con-button").removeClass("active");
$("#c-offline").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
})
getSteams();
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "maatukka", "Vinesauce", "brunofin", "comster404", "OgamingSC2"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.effect {
position: absolute;
left: 0;
transition: 0.4s ease-in-out;
}
.controls .effect {
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
height: 2px;
bottom: 5px;
background: #6441A4;
margin-left:/*-45px*/auto;
margin-right:/*-45px*/auto;
width: 33%;
}
button:nth-child(1).active ~ .effect {left: 0%;}
button:nth-child(2).active ~ .effect {left: 33%;}
button:nth-child(3).active ~ .effect {left: 66%;}
.divider hr {
border-top: 1px solid #6441A4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
I made sure that .active is working in Javascript but I still need help making the underline moving from one link to another when clicked. All I know is that it has something to do with the CSS. Any help or tutorials are appreciated.
You can use this simple technique if you can use jQuery. It is quite generic and you can use any html elements whether nav, buttons or simple div's. You just need to have an outer element that contains all your links.
The idea is to find the position and width of the clicked anchor tag and then apply the same(or after adding some modification) to the underline element. To make its movement smooth you can add transition for left and width properties of this underline element.
$("#outer-container a").on("click", function(e){
e.preventDefault();
var cssObj = {};
cssObj.left = $(this).position().left;
cssObj.width = $(this).outerWidth();
$("#outer-container #underline").css( cssObj );
});//a click()
$("#outer-container a").eq(0).trigger("click");
#outer-container
{
text-align: center;
position: relative;
}
#outer-container a
{
color: #333;
display: inline-block;
padding: 0 10px;
text-decoration: none;
}
#outer-container #underline
{
content: "";
display: block;
position: absolute;
bottom: 0;
left: 0;
height: 2px;
width: 100px;
background-color: #333;
transition: left 0.3s ease, width 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="outer-container">
One
Two
Three
Four
<span id="underline"></span>
</div><!--#outer-container-->
Checkout this,
$(document).ready(function() {
$(".con-button").click(function(){
if(this.id == "c-all") {
$(".con-button").removeClass("active");
$("#c-all").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$(".con-button").removeClass("active");
$("#c-online").addClass("active");
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$(".con-button").removeClass("active");
$("#c-offline").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
})
getSteams();
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "maatukka", "Vinesauce", "brunofin", "comster404", "OgamingSC2"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.effect {
position: absolute;
left: 0;
transition: 0.4s ease-in-out;
}
.controls .effect {
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
height: 2px;
bottom: 5px;
background: #6441A4;
margin-left:/*-45px*/auto;
margin-right:/*-45px*/auto;
width: 33%;
}
button:nth-child(1).active ~ .effect {left: 0%;}
button:nth-child(2).active ~ .effect {left: 33%;}
button:nth-child(3).active ~ .effect {left: 66%;}
.divider hr {
border-top: 1px solid #6441A4;
}
.effect {
position: absolute;
left: 18%;
transition: 0.4s ease-in-out;
}
.controls button:nth-child(1).active ~ .effect {
left: 28%;
/* the middle of the first <a> */
}
.controls button:nth-child(2).active ~ .effect {
left: 50%;
/* the middle of the second <a> */
}
.controls button:nth-child(3).active ~ .effect {
left: 77%;
/* the middle of the third <a> */
}
.controls button:nth-child(4).active ~ .effect {
left: 93.5%;
/* the middle of the forth <a> */
}
.controls .effect {
width: 55px;
height: 2px;
bottom: 5px;
background: #00ABE8;
margin-left:-45px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
<div class="effect"></div>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
I have made changes in your code to make it work.
I'm working on transitions by using javascript. But i want to display element to none when the transition is end. I'm using addEventListener on element but function doesn't execute.
var fun;
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
};
(function(){
var i=0,
containterget = document.querySelector('.container');
elementGet = document.querySelector('.Number');
fun = function(){
i++;
elementGet.innerHTML = i;
elementGet.style.transform = 'translateX('+(containterget.offsetWidth - 40 -35)+'px)';
elementGet.addEventListener(transitions,function(event){
console.log("Transition End Execute");
elementGet.style.display='none';
} );
};
})();
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.container{
border:1px solid green;
max-width:85%;
margin: 2em auto 0;
}
button{
background-color:transparent;
padding: 15px;
margin:0;
color:#000;
border:2px solid #F44336;
text-align: center;
outline: 0;
transition: opacity 0.3s;
}
button:hover{
background-color:#F44336;
color: white;
opacity :.75;
}
button:hover{
cursor: pointer;
transition: opacity .4s;
}
span{
display: inline-block;
transition: transform 1.5s ease;
}
.Number{
font-size: 4em;
border:1px solid black;
/*transform: translateX(0);*/
}
.EndBoundry{
float: right;
font-size: 4em;
border:1px solid black;
}
.contain:after{
content: "";
display: table;
clear: both;
}
.btn{
text-align: center;
margin: 2em 0;
}
<div class="container contain">
<span class="Number">1</span>
<span class="EndBoundry">E</span>
</div>
<div class="btn">
<button onclick="fun()">Number Transition Click</button>
</div>
The following Snippet demonstrates the transitionend event. All details are commented in Snippet.
SNIPPET
// Reference the section#area and input#gone
var area = document.getElementById('area');
var chx = document.getElementById('gone');
// Register click event on #area call offON()
area.addEventListener('click', offON, false);
function offON(e) {
// Determine the clicked button
if (e.target !== e.currentTarget) {
var tgt = e.target;
// Switch clicked button classes .on and .off
tgt.classList.toggle('on');
tgt.classList.toggle('off');
}
// If the checkbox is checked call transEND()
if (chx.checked) {
transEND()
}
}
function transEND() {
// Register the transitionend event on #area
area.addEventListener("transitionend", function(e) {
// Determine which button was clicked
if (e.target !== e.currentTarget) {
var tgt = e.target;
// Clicked button will disappear after transition
tgt.style.display = 'none';
}
}, false);
}
/* All buttons will have the same
|| transition. This transition is
|| dependent upon another animatable
|| style to exist.
*/
/* This particular transition says:
|| ALL animatable styles have a
|| duration of 3 seconds,
|| with a timing function: ease,
|| and a delay of 300msec
*/
button {
width: 120px;
height: 40px;
transition: all 3s ease .3s
}
/* Classes .on and .off are "states"
|| to each #id the "states" have a
|| different meaning
*/
#fade.off {
opacity: 1;
}
#fade.on {
opacity: 0;
}
#move.off {
transform: translateY(0);
}
#move.on {
transform: translateY(200px);
}
#shrink.off {
transform: scale(1);
}
#shrink.on {
transform: scale(.3);
}
#gone {
width: 18px;
height: 18px;
}
p {
font-size: 12px;
}
<p>Click each button. Then click them again (the "FADER" is still there and clickable)</p>
<p>Now click the checkbox and push the buttons again. If you can't click the buttons back to original "state", then the event handler on transitionend was successful.</p>
<label for='gone'>Enable "transitionEND" </label>
<input id='gone' type='checkbox'>
<section id='area'>
<button id='fade' class='off'>FADER</button>
<button id='move' class='off'>MOVER</button>
<button id='shrink' class='off'>SHRINKER</button>
</section>
Use "transitionend" without prefixes
elementGet.addEventListener("transitionend", function(){});
You can listen to transitionend event on supported browsers.
I did some reshuffling of your codes and add an id tag to your button.
See snippet below
var fun;
var i = 0,
containterget = document.querySelector('.container');
elementGet = document.querySelector('.Number');
console.log(elementGet)
function execute(event) {
console.log("Transition End Execute");
alert("Transition End Execute");
elementGet.style.display = 'none';
}
fun = function() {
i++;
elementGet.innerHTML = i;
elementGet.style.transform = 'translateX(' + (containterget.offsetWidth - 40 - 35) + 'px)';
elementGet.addEventListener('transitionend', execute);
elementGet.addEventListener('webkitTransitionEnd', execute);
elementGet.addEventListener('mozTransitionEnd', execute);
elementGet.addEventListener('oTransitionEnd', execute);
};
document.getElementById("target").addEventListener("click", fun)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
border: 1px solid green;
max-width: 85%;
margin: 2em auto 0;
}
button {
background-color: transparent;
padding: 15px;
margin: 0;
color: #000;
border: 2px solid #F44336;
text-align: center;
outline: 0;
transition: opacity 0.3s;
}
button:hover {
background-color: #F44336;
color: white;
opacity: .75;
}
button:hover {
cursor: pointer;
transition: opacity .4s;
}
span {
display: inline-block;
transition: transform 1.5s ease;
}
.Number {
font-size: 4em;
border: 1px solid black;
/*transform: translateX(0);*/
}
.EndBoundry {
float: right;
font-size: 4em;
border: 1px solid black;
}
.contain:after {
content: "";
display: table;
clear: both;
}
.btn {
text-align: center;
margin: 2em 0;
}
<div class="container contain">
<span class="Number">1</span>
<span class="EndBoundry">E</span>
</div>
<div class="btn">
<script></script>
<button id="target">Number Transition Click</button>
</div>
I am currently writing a program which toggles a value based on the status of a checkbox. With a normal checkbox everything works fine.
HTML:
<td><script> checkbox('px_THPressure_Enable')</script></td>
<td><script> checkbox('px_THPressure_Activate')</script></td>
Javascript checkbox function:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<input type='checkbox' class='fetch' onClick=\""+onClicked+"\" id='" + register + "'>";
document.write(output);
}
Now I am trying to style the checkbox with CSS as described here http://www.paulund.co.uk/style-checkboxes-with-css "Checkbox Four"
So now my checkbox function changed to:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<div class='checkboxFour'><input type='checkbox' class='fetch' value='1' onClick=\""+onClicked+"\" id='" + register + "' name=''></input><label for='checkboxFourInput'></label></div>";
document.write(output);
}
CSS:
input[type=checkbox] {
visibility: hidden;
}
/**
* Checkbox Four
*/
.checkboxFour {
width: 40px;
height: 40px;
background: #ddd;
margin: 20px 90px;
border-radius: 100%;
position: relative;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checkbox button
*/
.checkboxFour label {
display: block;
width: 30px;
height: 30px;
border-radius: 100px;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
-o-transition: all .5s ease;
-ms-transition: all .5s ease;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 5px;
left: 5px;
z-index: 1;
background: #333;
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checked state
*/
.checkboxFour input[type=checkbox]:checked + label {
background: #26ca28;
}
Now I am able to see the correct status of the checkbox with the new style but when I click the checkbox the value does not change. I know that the issue is in the id field. The checkbox style requires the id="checkboxFourInput" and my program requires the id to equal the register value which is being toggled. ie THPressure_Enable
I know that having multiple ids on an html element is not allowed, so is there any way that I can toggle this register value with the styled checkbox.
Thank you in advance.
EDIT:
It is a function that will change the register value depending on the correct authorization. I have the function defined as follows:
function setDataJQuery(register,value)
{
statusElem = document.getElementById('status');
if (statusElem)
statusElem.innerHTML=" ";
//alert("logged in as " + "<?php echo \"{$_SERVER['PHP_AUTH_USER']}\"; ?>");
if (((user_name == 'slipsmart' || user_name== 'slipsmart_super') && (operator_set_ok.indexOf(register.substring(3)) != -1)) ||
(user_name == 'slipsmart_super' && (supervisor_set_ok.indexOf(register.substring(3)) != -1)) ||
user_name == 'slipsmart_setup')
{
$.ajax({
url: 'set.php?' + register + '=' + value,
type: 'post',
success:function(data){
var val_pairs = data.split("&");
document.getElementById('Error').innerHTML=" ";
for (i in val_pairs)
{
var pair = val_pairs[i].split("=");
var myElem = document.getElementById(pair[0]);
if (myElem)
myElem.innerHTML= pair[1];
}
}
});
}
else
alert("Not authorized!");
}