using multiple instances of popup - javascript
i am using a popup that perfectly suits my needs! what i want to do is add another instance of the same popup but its not working,basically i have two different popup i want to show depending on the scenario like one for register and one for login. the first instance named somedialog works fine but the instance somedialog2 doesn't work here's my code
<a data-dialog="somedialog" class="trigger icon icon-register">Register</a>
<a data-dialog="somedialog2" class="trigger icon icon-login">Login</a>
<div id="somedialog" class="dialog dialog--close">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<div class="morph-shape">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 560 280" preserveAspectRatio="none">
<rect x="3" y="3" fill="none" width="556" height="276"></rect>
</svg>
</div>
<div class="dialog-inner">
<h2><strong>Wait!</strong>, Are you a teacher or a student?</h2>
<div>
<button style="display: none" class="action" data-dialog-close="a">Close</button>
<button class="action" onclick="window.location.href='<?=base_url()?>Home/student_register'">I'm A Student</button>
<button class="action" onclick="window.location.href='<?=base_url()?>Home/teacher_register'">I'm A Teacher</button>
</div>
</div>
</div>
</div>
<div id="somedialog2" class="dialog dialog--close">
<h1>here</h1>
<div class="dialog__overlay"></div>
<div class="dialog__content">
<div class="morph-shape">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 560 280" preserveAspectRatio="none">
<rect x="3" y="3" fill="none" width="556" height="276"></rect>
</svg>
</div>
<div class="dialog-inner">
<h2><strong>Wait!</strong>, Are you a teacher or a student?</h2>
<div>
<button style="display: none" class="action" data-dialog-close="a">Close</button>
<button class="action" onclick="window.location.href='<?=base_url()?>Student'">I'm A Student</button>
<button class="action" onclick="window.location.href='<?=base_url()?>Teacher'">I'm A Teacher</button>
</div>
</div>
</div>
</div>
js
( function( window ) {
'use strict';
var support = { animations : Modernizr.cssanimations },
animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' },
animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ],
onEndAnimation = function( el, callback ) {
var onEndCallbackFn = function( ev ) {
if( support.animations ) {
if( ev.target != this ) return;
this.removeEventListener( animEndEventName, onEndCallbackFn );
}
if( callback && typeof callback === 'function' ) { callback.call(); }
};
if( support.animations ) {
el.addEventListener( animEndEventName, onEndCallbackFn );
}
else {
onEndCallbackFn();
}
};
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function DialogFx( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this.ctrlClose = this.el.querySelector( '[data-dialog-close]' );
this.isOpen = false;
this._initEvents();
}
DialogFx.prototype.options = {
// callbacks
onOpenDialog : function() { return false; },
onCloseDialog : function() { return false; }
}
DialogFx.prototype._initEvents = function() {
var self = this;
// close action
this.ctrlClose.addEventListener( 'click', this.toggle.bind(this) );
// esc key closes dialog
document.addEventListener( 'keydown', function( ev ) {
var keyCode = ev.keyCode || ev.which;
if( keyCode === 27 && self.isOpen ) {
self.toggle();
}
} );
this.el.querySelector( '.dialog__overlay' ).addEventListener( 'click', this.toggle.bind(this) );
}
DialogFx.prototype.toggle = function() {
var self = this;
if( this.isOpen ) {
classie.remove( this.el, 'dialog--open' );
classie.add( self.el, 'dialog--close' );
onEndAnimation( this.el.querySelector( '.dialog__content' ), function() {
classie.remove( self.el, 'dialog--close' );
} );
// callback on close
this.options.onCloseDialog( this );
}
else {
classie.add( this.el, 'dialog--open' );
// callback on open
this.options.onOpenDialog( this );
}
this.isOpen = !this.isOpen;
};
// add to global namespace
window.DialogFx = DialogFx;
})( window );
(function() {
var dlgtrigger = document.querySelector( '[data-dialog]' );
console.log(dlgtrigger);
var dlgtrigger = document.querySelector( '[data-dialog]' ),
somedialog = document.getElementById( dlgtrigger.getAttribute( 'data-dialog' ) ),
dlg = new DialogFx( somedialog );
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
})();
(function() {
var dlgtrigger = document.querySelector( '[data-dialog]' );
console.log(dlgtrigger);
var dlgtrigger = '<a class="trigger icon icon-register" data-dialog="somedialog">',
somedialog = "somedialog2",
dlg = new DialogFx( somedialog );
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
})();
Codepen
This should do it,, the problem that you had was that your code only targeted one element id,, I only expanded it to account for all elements that have [data-dialog] property..
/**
* dialog box v0.1
* Ashwin Saxena
*/
;
(function(window) {
'use strict';
var support = {
animations: Modernizr.cssanimations
},
animEndEventNames = {
'WebkitAnimation': 'webkitAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd',
'animation': 'animationend'
},
animEndEventName = animEndEventNames[Modernizr.prefixed('animation')],
onEndAnimation = function(el, callback) {
var onEndCallbackFn = function(ev) {
if (support.animations) {
if (ev.target != this) return;
this.removeEventListener(animEndEventName, onEndCallbackFn);
}
if (callback && typeof callback === 'function') {
callback.call();
}
};
if (support.animations) {
el.addEventListener(animEndEventName, onEndCallbackFn);
} else {
onEndCallbackFn();
}
};
function extend(a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
}
function DialogFx(el, options) {
this.el = el;
this.options = extend({}, this.options);
extend(this.options, options);
this.ctrlClose = this.el.querySelector('[data-dialog-close]');
this.isOpen = false;
this._initEvents();
}
DialogFx.prototype.options = {
// callbacks
onOpenDialog: function() {
return false;
},
onCloseDialog: function() {
return false;
}
}
DialogFx.prototype._initEvents = function() {
var self = this;
// close action
this.ctrlClose.addEventListener('click', this.toggle.bind(this));
// esc key closes dialog
document.addEventListener('keydown', function(ev) {
var keyCode = ev.keyCode || ev.which;
if (keyCode === 27 && self.isOpen) {
self.toggle();
}
});
this.el.querySelector('.dialog__overlay').addEventListener('click', this.toggle.bind(this));
}
DialogFx.prototype.toggle = function() {
var self = this;
if (this.isOpen) {
classie.remove(this.el, 'dialog--open');
classie.add(self.el, 'dialog--close');
onEndAnimation(this.el.querySelector('.dialog__content'), function() {
classie.remove(self.el, 'dialog--close');
});
// callback on close
this.options.onCloseDialog(this);
} else {
classie.add(this.el, 'dialog--open');
// callback on open
this.options.onOpenDialog(this);
}
this.isOpen = !this.isOpen;
};
// add to global namespace
window.DialogFx = DialogFx;
})(window);
/* call */
(function() {
var dlgs = document.querySelectorAll('[data-dialog]');
for( var i = 0; i < dlgs.length; i++){
var dlgID = document.getElementById(dlgs[i].getAttribute('data-dialog'));
var dlg = new DialogFx( dlgID );
dlgs[i].addEventListener('click', dlg.toggle.bind(dlg));
}
})();
button {
padding: 1em 2em;
outline: none;
font-weight: 600;
border: none;
color: #fff;
background: #c94e50;
}
.dialog,
.dialog__overlay {
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.dialog {
position: fixed;
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
pointer-events: none;
}
.dialog__overlay {
position: absolute;
z-index: 1;
background: rgba(55, 58, 71, 0.9);
opacity: 0;
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s;
-webkit-backface-visibility: hidden;
}
.dialog--open .dialog__overlay {
opacity: 1;
pointer-events: auto;
}
.dialog__content {
width: 50%;
max-width: 560px;
min-width: 290px;
background: #fff;
padding: 4em;
text-align: center;
position: relative;
z-index: 5;
opacity: 0;
}
.dialog--open .dialog__content {
pointer-events: auto;
}
/* Content */
.dialog h2 {
margin: 0;
font-weight: 400;
font-size: 2em;
padding: 0 0 2em;
margin: 0;
}
.dialog--open .dialog__overlay {
-webkit-transition-duration: 0.8s;
transition-duration: 0.8s;
}
.dialog--close .dialog__overlay {
-webkit-transition-duration: 0.5s;
transition-duration: 0.5s;
}
.dialog__content {
padding: 0;
background: transparent;
}
.dialog.dialog--open .dialog__content {
opacity: 1;
}
.morph-shape {
position: absolute;
width: calc(100% + 4px);
height: calc(100% + 4px);
top: -2px;
left: -2px;
z-index: -1;
}
.morph-shape svg rect {
stroke: #fff;
stroke-width: 2px;
stroke-dasharray: 1680;
}
.dialog--open .morph-shape svg rect {
-webkit-animation: anim-dash 0.6s forwards;
animation: anim-dash 0.6s forwards;
}
.dialog-inner {
opacity: 0;
background: #fff;
}
.dialog--open .dialog-inner {
padding: 4em;
opacity: 1;
-webkit-transition: opacity 0.85s 0.35s;
transition: opacity 0.85s 0.35s;
}
.dialog.dialog--open h2 {
-webkit-animation: anim-elem-1 0.7s ease-out both;
animation: anim-elem-1 0.7s ease-out both;
}
.dialog.dialog--open button {
-webkit-animation: anim-elem-2 0.7s ease-out both;
animation: anim-elem-2 0.7s ease-out both;
}
#keyframes anim-dash {
0% {
stroke-dashoffset: 1680;
}
100% {
stroke-dashoffset: 0;
}
}
#-webkit-keyframes anim-dash {
0% {
stroke-dashoffset: 1680;
}
100% {
stroke-dashoffset: 0;
}
}
/* Inner elements animations */
#-webkit-keyframes anim-elem-1 {
0% {
opacity: 0;
-webkit-transform: translate3d(-150px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
}
}
#keyframes anim-elem-1 {
0% {
opacity: 0;
-webkit-transform: translate3d(-150px, 0, 0);
transform: translate3d(-150px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
#-webkit-keyframes anim-elem-2 {
0% {
opacity: 0;
-webkit-transform: translate3d(150px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
}
}
#keyframes anim-elem-2 {
0% {
opacity: 0;
-webkit-transform: translate3d(150px, 0, 0);
transform: translate3d(150px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://tympanus.net/Development/DialogEffects/js/classie.js"></script>
<script src="https://tympanus.net/Development/DialogEffects/js/modernizr.custom.js"></script>
<div class="button-wrap">
<button data-dialog="somedialog" class="trigger">Open Dialog 1</button>
</div>
<div class="button-wrap">
<button data-dialog="somedialog1" class="trigger">Open Dialog 2</button>
</div>
<div id="somedialog" class="dialog dialog--close">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<div class="morph-shape">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 560 280" preserveAspectRatio="none">
<rect x="3" y="3" fill="none" width="556" height="276"></rect>
</svg>
</div>
<div class="dialog-inner">
<h2><strong>Howdy</strong>, I'm a dialog box 1</h2>
<div><button class="action" data-dialog-close="a">Close</button></div>
</div>
</div>
</div>
<div id="somedialog1" class="dialog dialog--close">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<div class="morph-shape">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 560 280" preserveAspectRatio="none">
<rect x="3" y="3" fill="none" width="556" height="276"></rect>
</svg>
</div>
<div class="dialog-inner">
<h2><strong>Howdy</strong>, I'm a dialog box 2</h2>
<div><button class="action" data-dialog-close="a">Close</button></div>
</div>
</div>
</div>
Related
jQuery response() function doesn't return any results because of the variable scope
The problem I encountered is I can't get any results from the jQuery UI Autocomplete form because of the variable scope. Let me show you. // TAKE A CLOSE LOOK AT THIS METHOD select: function(e, ui) { $('#instant-search').text(ui.item.label); $("#search").autocomplete("option", "source", function(request, response) { getAutocompleteResults(function(d) { // DOESN'T WORK response(d); }); // WORKS BUT IT SHOULD BE A DYNAMIC ARRAY FROM THE "D" OBJECT // response(["anarchism", "anarchist black cross", "black rose (symbolism)", "communist symbolism", "political symbolism"]); }); $("#search").autocomplete("search", ui.item.label); In order to return results I have to use a function response([...]); outside the getAutocompleteResults(function(d) { ... }); function. However, the source should be dynamic and not like the static array. In other words: The function response(d); should return an object, which contains a few properties (title, value, extract). I have to access them by using response(d);, however, this function doesn't work inside getAutocompleteResults(function(d) { ... }); function. How can I achieve this? There is a small snippet of code, however, the main problem is the select method. You can find this in the middle of the whole code block. I commented it out. $(function() { $("html").removeClass("no-js"); var autocompleteResults = [{ title: [], extract: [], pageId: [] }]; var capitalizeFirstLetter = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; var changeText2 = function(e) { var request = $("input").val() + String.fromCharCode(e.which); $("#instant-search").text(request); var getAutocompleteResults = function(callback) { $.ajax({ url: "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrlimit=6&prop=extracts&origin=*&pilimit=max&exintro&explaintext&exsentences=1&gsrsearch=" + $("#instant-search").text(), beforeSend: function() { $(".loading").show(); }, success: function(d) { $(".loading").hide(); autocompleteResults[0].title = []; autocompleteResults[0].extract = []; autocompleteResults[0].pageId = []; if (d.hasOwnProperty("query")) { if (d.query.hasOwnProperty("pages")) { $.each(d.query.pages, function(i) { autocompleteResults[0].title.push(d.query.pages[i].title); autocompleteResults[0].extract.push(d.query.pages[i].extract); autocompleteResults[0].pageId.push(d.query.pages[i].pageid); }); } } if (!autocompleteResults[0].length) { $(".ui-autocomplete").hide(); } autocompleteResults[0].title.sort(function(a, b) { var nameA = a.toUpperCase(); var nameB = b.toUpperCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; }); autocompleteResults[0].title = autocompleteResults[0].title.map( function(i) { return i.toLowerCase(); } ); callback(autocompleteResults[0]); }, datatype: "json", cache: false }); }; $("#search").autocomplete({ source: function(request, response) { getAutocompleteResults(function(d) { var results = [], filteredAutocompleteResults = []; filteredAutocompleteResults = d.title.filter(function(i) { return ( i != $("#instant-search") .text() .toLowerCase() ); }); for (var i = 0; i < d.title.length; i++) { results[i] = { label: filteredAutocompleteResults[i], extract: d.extract[i], pageId: d.pageId[i] }; } if (results.length == 5) { response(results); } else { response(results.slice(0, 5)); } }); }, response: function() { if ($("#instant-search").text()) { $("table").css("display", "table"); $(".wikisearch-container").css("margin-top", 100); } }, close: function() { if (!$(".ui-autocomplete").is(":visible")) { $(".ui-autocomplete").show(); } }, appendTo: ".input", focus: function(e) { e.preventDefault(); }, delay: 0, // TAKE A CLOSE LOOK AT THIS METHOD select: function(e, ui) { $('#instant-search').text(ui.item.label); $("#search").autocomplete("option", "source", function(request, response) { getAutocompleteResults(function(d) { // DOESN'T WORK response(d); }); // WORKS BUT IT SHOULD BE A DYNAMIC ARRAY FROM THE "D" OBJECT // response(["anarchism", "anarchist black cross", "black rose (symbolism)", "communist symbolism", "political symbolism"]); }); $("#search").autocomplete("search", ui.item.label); // EVERYTHING SHOULD BE FINE BELOW THIS LINE if ($(".search-results").css("opacity") != 1) { $(".search-results h4").text(capitalizeFirstLetter(ui.item.label)); $(".search-results p").text(ui.item.extract); $(".search-results a").prop( "href", "https://en.wikipedia.org/?curid=" + ui.item.pageId ); $(".search-results").css("opacity", 1); } else if ( $(".search-results h4") .text() .toLowerCase() != ui.item.label ) { $(".search-results").css("opacity", 0); setTimeout(function() { $(".search-results h4").text(capitalizeFirstLetter(ui.item.label)); $(".search-results p").text(ui.item.extract); $(".search-results a").prop( "href", "https://en.wikipedia.org/?curid=" + ui.item.pageId ); $(".search-results").css("opacity", 1); }, 500); } }, create: function() { $(this).data("ui-autocomplete")._renderItem = function(ul, item) { return $("<li>") .append( '<div class="ui-menu-item-wrapper"><div class="autocomplete-first-field"><i class="fa fa-search" aria-hidden="true"></i></div><div class="autocomplete-second-field three-dots">' + item.label + "</div></div>" ) .appendTo(ul); }; } }); }; var changeText1 = function(e) { if ( /[-a-z0-90áãâäàéêëèíîïìóõôöòúûüùçñ!##$%^&*()_+|~=`{}\[\]:";'<>?,.\s\/]+/gi.test( String.fromCharCode(e.which) ) ) { $("input").on("keypress", changeText2); } // DONT TOUCH THIS AREA, IT HAS NOTHING TO DO WITH THE PROBLEM var getInputSelection = function(input) { var start = 0, end = 0; input.focus(); if ( typeof input.selectionStart == "number" && typeof input.selectionEnd == "number" ) { start = input.selectionStart; end = input.selectionEnd; } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); if (range) { var inputRange = input.createTextRange(); var workingRange = inputRange.duplicate(); var bookmark = range.getBookmark(); inputRange.moveToBookmark(bookmark); workingRange.setEndPoint("EndToEnd", inputRange); end = workingRange.text.length; workingRange.setEndPoint("EndToStart", inputRange); start = workingRange.text.length; } } return { start: start, end: end, length: end - start }; }; switch (e.key) { case "Backspace": case "Delete": e = e || window.event; var keyCode = e.keyCode; var deleteKey = keyCode == 46; var sel, deletedText, val; val = this.value; sel = getInputSelection(this); if (sel.length) { // 0 kai paprastai trini po viena o 1 ar daugiau kai select su pele trini $("#instant-search").text( val.substr(0, sel.start) + val.substr(sel.end) ); } else { $("#instant-search").text( val.substr(0, deleteKey ? sel.start : sel.start - 1) + val.substr(deleteKey ? sel.end + 1 : sel.end) ); } break; case "Enter": if ($("#instant-search").text()) { console.log("Redirecting..."); } break; } if (!$("#instant-search").text()) { $("table, .ui-autocomplete").hide(); $(".wikisearch-container").css("margin-top", ""); } if ( $(".ui-menu-item-wrapper").hasClass("ui-state-active") && (e.key == "ArrowRight" || e.key == "ArrowLeft") ) { $(".ui-autocomplete").autocomplete(""); // Error metas console ir taip neturėtų būti bet nežinau kaip padaryti kad pasirinkus elementą su <-- ar --> nepadarytų tik vieno rezultato todėl paliekam laikinai ;) } }; $("input").on("keydown", changeText1); $("input").on("input", function(e) { $("#instant-search").text($("#search").val()); }); }); html, body { height: 100%; width: 100%; } body { margin: 0; padding: 0; font-family: sans-serif; background-image: url("http://www.part.lt/img/96816a00ec1fb87adc4ca8a04365b2b5719.jpg"); background-size: cover; background-position: 100%; } .v-container { display: table; height: 100%; width: 100%; } .v-content { display: table-cell; vertical-align: middle; } .text-center { text-align: center; } .input { overflow: hidden; white-space: nowrap; } .input input#search { width: calc(100% - 30px); height: 50px; border: none; font-size: 10pt; float: left; color: #4f5b66; padding: 0 15px; outline: none; } .ui-autocomplete { list-style: none; background-color: #fff; -webkit-user-select: none; user-select: none; padding: 0; margin: 0; width: 100% !important; top: auto !important; display: table; table-layout: fixed; } .ui-helper-hidden-accessible { display: none; } .autocomplete-first-field { width: 15%; display: inline-block; } .autocomplete-second-field { width: 85%; display: inline-block; text-align: left; vertical-align: middle; } .three-dots { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } table { width: 100%; border-spacing: 0; border-collapse: collapse; display: none; table-layout: fixed; } table tr { background-color: #fff; -webkit-user-select: none; user-select: none; } tr:first-child { background-color: #ffc800; color: #fff; } table td, .ui-menu-item-wrapper { padding: 10px 0; } td:nth-child(2) { width: 85%; text-align: left; } .ui-menu-item, table { cursor: pointer; } :focus { outline: 0; } a { text-decoration: none; color: #fff; position: relative; } a:before { content: ""; position: absolute; width: 100%; height: 0.0625rem; bottom: 0; left: 0; background-color: #fff; visibility: hidden; -webkit-transform: scaleX(0); transform: scaleX(0); -webkit-transition: all 0.3s ease-in-out 0s; transition: all 0.3s ease-in-out 0s; } a:hover:before { visibility: visible; -webkit-transform: scaleX(1); transform: scaleX(1); } .search-results { background: #fff; margin-top: 50px; border-left: 5px solid #0ebeff; opacity: 0; -webkit-transition: opacity 1s; transition: opacity 1s; } .search-results h4, .search-results p { margin: 0; padding: 10px; text-align: left; } .search-results a { color: #0ebeff; display: inline-block; margin: 1rem 0; } .search-results a:before { background-color: #0ebeff; } .wikisearch-container { width: 65%; margin: 0 auto; } /* Loading animation */ #keyframes lds-eclipse { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } #-webkit-keyframes lds-eclipse { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } .loading { position: relative; top: 9.5px; right: 15px; pointer-events: none; display: none; } .lds-eclipse { -webkit-animation: lds-eclipse 1s linear infinite; animation: lds-eclipse 1s linear infinite; width: 2rem; height: 2rem; border-radius: 50%; margin-left: auto; box-shadow: 0.08rem 0 0 #0ebeff; } #media (max-width: 71.875em) { .wikisearch-container { width: 75%; } } #media (max-width: 50em) { .wikisearch-container { width: 85%; } } #media (max-width: 17.96875em) { .wikisearch-container { width: 100%; } } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <html class="no-js"> <div class="v-container"> <div class="v-content text-center"> <div class="wikisearch-container"> <div class="input"> <input type="text" id="search" placeholder="Search..."> <div class="loading"> <div class="lds-eclipse"></div> </div> <button class="icon"><i class="fa fa-search"></i></button> <table> <tr> <td class="fa fa-search"> <td id="instant-search" class="three-dots"></td> </tr> </table> </div> <div class="search-results"> <h4></h4> <p></p> <a target="_blank">Click here for more</a> </div> </div> </div> </div> EDIT 1 After some changes, the results are shown, however, before the ajax call. How can I use response() only after the ajax was successfully completed (tried using success callback, didn't work :()? Full project code: https://codepen.io/Kestis500/pen/zRONyw?editors=0010. Here you can see step by step how it looks like: How it looks like when you just reloaded the page: Let's try entering "a": We've got some results. Ok, let's try to click on the "anarchist symbolism" element: Results should look like "anarchist symbolism" search. However, it returns the result of the "a" search. What if we pressed "fraktur" element? Now it shows our previous search "anarchist symbolism" results. However, it should return elements of the "fraktur" search. EDIT 2 I've fixed many things and removed some really non sense things from my code. However, the situation with the ajax call is still the same. https://codepen.io/Kestis500/pen/pazppP?editors=0110 Any ideas? EDIT 3 Fixed ajax lag (now the ajax request will be sent only after the previous ajax call). https://codepen.io/Kestis500/pen/JpPLON?editors=0110
I had to first fix a few things in your Ajax call. We then collect the results and build an array that should be returned to response(). This will populate the AutoComplete. First we will examine the HTML. There was some closing tags missing. HTML <div class="v-container"> <div class="v-content text-center"> <div class="wikisearch-container"> <div class="input ui-front"> <input type="text" id="search" placeholder="Search..."> <div class="loading"> <div class="lds-eclipse"></div> </div> <button class="icon"> <i class="fa fa-search"></i> </button> <table> <tr> <td class="fa fa-search"></td> <td id="instant-search" class="three-dots"></td> </tr> </table> </div> <div class="search-results"> <h4></h4> <p></p> <a target="_blank">Click here for more</a> </div> </div> </div> </div> You can see the table and it's cells all have the proper closing tags now. I didn't make any changes to your CSS or Style. JavaScript $(function() { var capitalizeFirstLetter = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; $("#search").autocomplete({ source: function(request, response) { var results = []; $.ajax({ url: "https://en.wikipedia.org/w/api.php", data: { format: "json", action: "query", generator: "search", gsrlimit: 6, prop: "extracts|pageimages", origin: "*", pilimit: "max", exintro: false, explaintext: false, exsentences: 1, gsrsearch: request.term }, beforeSend: function() { $(".loading").show(); }, success: function(d) { $(".loading").hide(); if (d.query.pages) { $.each(d.query.pages, function(k, v) { console.log(k, v.title, v.extract, v.pageid); results.push({ label: v.title, value: "https://en.wikipedia.org/?curid=" + v.pageid, title: v.title, extract: v.extract, pageId: v.pageid }); }); response(results); } }, datatype: "json", cache: false }); response(results); }, close: function() { if (!$(".ui-autocomplete").is(":visible")) { $(".ui-autocomplete").show(); } }, focus: function(e) { e.preventDefault(); return false; }, delay: 0, select: function(e, ui) { if ($(".search-results").css("opacity") != 1) { $(".search-results h4").text(capitalizeFirstLetter(ui.item.label)); $(".search-results p").text(ui.item.extract); $(".search-results a").prop( "href", ui.item.value ); $(".search-results").css("opacity", 1); } else if ( $(".search-results h4") .text() .toLowerCase() != ui.item.label ) { $(".search-results").css("opacity", 0); setTimeout(function() { $(".search-results h4").text(capitalizeFirstLetter(ui.item.label)); $(".search-results p").text(ui.item.extract); $(".search-results a").prop( "href", ui.item.value ); $(".search-results").css("opacity", 1); }, 500); } return false; } }).autocomplete("instance")._renderItem = function(ul, item) { var $item = $("<li>"); var $wrap = $("<div>").appendTo($item); var $field1 = $("<div>", { class: "autocomplete-first-field" }).appendTo($wrap); $("<i>", { class: "fa fa-search", "aria-hidden": true }).appendTo($field1); $("<div>", { class: "autocomplete-second-field three-dots" }).html(item.label).appendTo($wrap); return $item.appendTo(ul); }; }); There was a lot of things to fix and improve. Let's start with the Ajax. You're making a call to a MediaWiki API and expecting some results. When the call would come back, it would generate warnings about pilimit. Digging into the API docs, this is a parameter specific to the pageimages properties call. To fix this, the prop value had to be extracts|pageimages. Now I get a clean set of results. You can see I broke out the data so that I could more easily make changes and see what parameters I was sending to the API. Nothing wrong with your method, I just find this a lot easier to work with. This is all happening inside .autocomplete() when we are populating the source. When we use function as a source, it has to follow a few guidelines: we pass a request and response in results must be in an array the array can contain objects, as long as they contain at least { label, value } our results array must be passed to response function. A brief example: $(selector).autocomplete({ source: function(req, resp){ var q = req.term; // The Request is an object that contains 1 index: term // request.term will contain the content of our search var results = []; // An array to store the results $.getJSON("myapi.php", {query: q}, function(data){ $.each(data, function(key, val){ // iterate over the result data and populate our result array results.push({ label: data.name, value: data.url }); resp(results); }); }); } }); You can sort or filter the results all you like; as long as you pass them to response in the end. With your focus and select callbacks, you want to return false. This is discussed more here: http://jqueryui.com/autocomplete/#custom-data We also see a good example of rendering the menu item. I switched over to making jQuery objects versus raw HTML. You do what works best for you. Working Example: https://jsfiddle.net/Twisty/vr6gv2aw/4/ Hope this helps.
Detect CSS Animation Keyframes with Javascript
So I have a simple CSS animation (a circle that grows, and then shrinks back down). I am able to successfully use Javascript to detect the start and end of the animation, but can't figure out how to detect the individual keyframes of that animation. So my question is: how can I detect when the 50% keyframe has been reached in my animation? Demo: http://codepen.io/tymichaels/pen/Mprrxw HTML <div class="center"> <svg class="center circle-animation" xmlns="https://www.w3.org/TR/SVG/"> <g> <circle cx="65" cy="70" r=60 fill="#96CCFF" stroke-width="3" stroke="#8181F7"></circle> <text x="35" y="75" font-size="18" class="output">circle</text> </g> </svg> </div> CSS svg { width:150px;} text {color:#000; font-family: sans-serif; font-weight: bold;} .center{ margin-top:100px; text-align:center; padding-bottom:50px; } .circle-animation{ animation-delay:2s; animation-duration: 4s; animation-name: circle-animation; animation-direction: normal; animation-timing-function: linear; } #-webkit-keyframes circle-animation { 0% {transform: scale( 1 );} 50% {transform: scale( 2.25 );} 100% {transform: scale( 1 );} } JS window.onload = function() { var elm = document.querySelector('.circle-animation'); var op = document.querySelector('.output'); elm.addEventListener('animationend', function(e) { op.innerHTML = 'ended'; }); elm.addEventListener('animationstart', function(e) { op.innerHTML = 'started'; }); }
You can dispatch a custom event on animationstart with setInterval and clear the interval on animationend. window.onload = function() { var elm = document.querySelector('.circle-animation'); var op = document.querySelector('.output'); var eventOnAnimate = new Event('onanimate'); var time = 0; elm.addEventListener('animationend', function(e) { op.innerHTML = 'ended'; clearInterval(elm.interval); time = 0; }); elm.addEventListener('animationstart', function(e) { op.innerHTML = 'started'; time = 0; elm.interval = setInterval(function(){ eventOnAnimate.data = {sampleData: ++time}; elm.dispatchEvent(eventOnAnimate); }); }); elm.addEventListener('onanimate', function(e) { op.innerHTML = e.data.sampleData + 'ms'; }); } svg { width:150px;} text {color:#000; font-family: sans-serif; font-weight: bold;} .center{ margin-top:30px; text-align:center; padding-bottom:50px; } .circle-animation{ animation-delay:2s; animation-duration: 4s; animation-name: circle-animation; animation-direction: normal; animation-timing-function: linear; } #-webkit-keyframes circle-animation { 0% {transform: scale( 1 );} 50% {transform: scale( 2.25 );} 100% {transform: scale( 1 );} } <div class="center"> <svg class="center circle-animation" xmlns="https://www.w3.org/TR/SVG/"> <g> <circle cx="65" cy="70" r=60 fill="#96CCFF" stroke-width="3" stroke="#8181F7"></circle> <text x="35" y="75" font-size="18" class="output">circle</text> </g> </svg> </div>
There is no native event support for listening keyframe-by-keyframe, but you can create a workaround with setTimeout and window.getComputedStyle (to get the animation-duration property). Below is an onKeyframes utility which can be used to listen for an arbitrary number of keyframe events using a more intuitive percentage-based syntax: onKeyframes(elm, { 0: function() { op.textContent = 'started' }, 50: function() { op.textContent = 'midpoint' }, 100: function() { op.textContent = 'ended' } }) Demo Snippet: function onKeyframes(element, handlers) { var from = handlers[0] || handlers.from var to = handlers[100] || handlers.to delete handlers.from delete handlers[0] delete handlers.to delete handlers[100] handlers = Object.keys(handlers).map(function(k) { return [k, this[k]] }, handlers) element.addEventListener('animationstart', function() { from && from.apply(this, arguments) if (handlers.length) { var match = /(\d+)(m?)s/.exec(window.getComputedStyle(element).animationDuration) var duration = (match[2] ? 1 : 1e3) * match[1] handlers.forEach(function(pair) { setTimeout(pair[1], pair[0] / 100 * duration) }) } }) to && element.addEventListener('animationend', to) } window.onload = function() { var elm = document.querySelector('.circle-animation') var op = document.querySelector('.output') onKeyframes(elm, { 0: function() { op.textContent = 'started' }, 50: function() { op.textContent = 'midpoint' }, 100: function() { op.textContent = 'ended' } }) } svg { width: 150px; } text { color: #000; font-family: sans-serif; font-weight: bold; } .center { margin-top: 100px; text-align: center; padding-bottom: 50px; } .circle-animation { animation-delay: 2s; animation-duration: 4s; animation-name: circle-animation; animation-direction: normal; animation-timing-function: linear; } #-webkit-keyframes circle-animation { 0% { transform: scale( 1); } 50% { transform: scale( 2.25); } 100% { transform: scale( 1); } } <div class="center"> <svg class="center circle-animation" xmlns="https://www.w3.org/TR/SVG/"> <g> <circle cx="65" cy="70" r=60 fill="#96CCFF" stroke-width="3" stroke="#8181F7"></circle> <text x="35" y="75" font-size="18" class="output">circle</text> </g> </svg> </div>
Prevent random particles to appear where unnecessary scrollbars are triggered
How to prevent random particles to appear where unnecessary scrollbars are triggered? The background element can't be fixed-sized. I think the solution could be to only show particles on the visible part of the viewport and to leave a margin of a few pixels, but I don't know how to do it. // https://github.com/maxspeicher/jquery-sparkle (function($, window, document) { const defaults = { fill: "#fff", stroke: "#000", size: 20, delay: 0, duration: 1500, pause: 1000 }; const optionsKeys = ["fill", "stroke", "size", "delay", "duration", "pause"]; const optionsStrToObj = function(optionsStr) { const optionsArr = !!optionsStr ? optionsStr.split(" ") : []; var optionsObj = {}; for (var i=0; i<optionsArr.length; ++i) { optionsObj[optionsKeys[i]] = optionsArr[i]; } return optionsObj; }; $.fn.sparkle = function(options) { $.destroySparkle = $.destroySparkle || {}; const $this = this; const id = this.data("sparkle-id") || (new Date()).getTime() + Math.random(); if (options === "destroy" && this.find("svg").length > 0) { $.destroySparkle[id] = true; this.data("sparkle-id", null); } var settings; if (options instanceof Array) { for (var i=0; i<options.length; ++i) { $this.sparkle(optionsStrToObj(options[i])); } return; } else if (options instanceof Object) { settings = $.extend({}, defaults, options); } else { settings = defaults; } const cssAnimationAttr = "my-sparkle " + settings.duration + "ms infinite linear"; const $star = $('<svg class="my-sparkle" version="1.1" viewBox="0.0 0.0 50.0 50.0" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><clipPath id="p.0"><path d="m0 0l50.0 0l0 50.0l-50.0 0l0 -50.0z" clip-rule="nonzero"></path></clipPath><g clip-path="url(#p.0)"><path fill="' + settings.stroke + '" fill-opacity="0.0" d="m0 0l50.0 0l0 50.0l-50.0 0z" fill-rule="nonzero"></path><path fill="' + settings.fill + '" d="m0.62204725 25.0l20.068499 -4.323374l4.309454 -20.13332l4.309454 20.13332l20.068499 4.323374l-20.068499 4.323374l-4.309454 20.133318l-4.309454 -20.133318z" fill-rule="nonzero"></path><path stroke="' + settings.stroke + '" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m0.62204725 25.0l20.068499 -4.323374l4.309454 -20.13332l4.309454 20.13332l20.068499 4.323374l-20.068499 4.323374l-4.309454 20.133318l-4.309454 -20.133318z" fill-rule="nonzero"></path></g></svg>').css({ position: "absolute", width: settings.size, height: settings.size, zIndex: 9999 }); const w = this.width(); const h = this.height(); const getCoordinates = function() { return { left: Math.random() * w, top: Math.random() * h }; }; const placeStar = function(init) { const coords = getCoordinates(); if (init) { $this.append($star); } $star.css({ "-moz-animation": cssAnimationAttr, "-webkit-animation": cssAnimationAttr, animation: cssAnimationAttr, display: "block", left: coords.left, top: coords.top }); window.setTimeout(function() { $star.css({ "-moz-animation": null, "-webkit-animation": null, animation: null, display: "none" }); if (!$.destroySparkle[id]) { window.setTimeout(function() { placeStar(false); }, settings.pause); } else { $star.remove(); } }, settings.duration); }; if (this.css("position") === "static") { this.css("position", "relative"); } if (!$.destroySparkle[id] && options !== "destroy") { window.setTimeout(function() { placeStar(true); }, settings.delay); this.data("sparkle-id", id); } return this; }; $("#bg").sparkle({ size: 25, }).sparkle({ delay: 1000, pause: 750, size: 25 }).sparkle({ delay: 1500, pause: 750, size: 25 }).sparkle({ delay: 2000, pause: 750, size: 25 }).sparkle({ delay: 2500, pause: 750, size: 25 }).sparkle({ delay: 3000, pause: 750, size: 25 }); })(Zepto, window, document); #-moz-keyframes my-sparkle { 0% { opacity: 0; -moz-transform: rotate(0deg) scale(0); } 50% { opacity: 1; -moz-transform: rotate(360deg) scale(1); } 100% { opacity: 0; -moz-transform: rotate(720deg) scale(0); } } #-webkit-keyframes my-sparkle { 0% { opacity: 0; -webkit-transform: rotate(0deg) scale(0); } 50% { opacity: 1; -webkit-transform: rotate(360deg) scale(1); } 100% { opacity: 0; -webkit-transform: rotate(720deg) scale(0); } } #keyframes my-sparkle { 0% { opacity: 0; transform: rotate(0deg) scale(0); } 50% { opacity: 1; transform: rotate(360deg) scale(1); } 100% { opacity: 0; transform: rotate(720deg) scale(0); } } body { background-color: #1d1f20; margin: 0; padding: 20px; } #bg { color: #666; display: inline-block; font-family: Verdana; font-size: 200%; font-weight: bold; } <script src="http://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script> <html id="bg" style="width: 100%; height: 100%;"> <head> <meta charset="UTF-8"> <title>Sparkles</title> </head> <body> <div>Sparkle, sparkle!</div> </body> </html> https://codepen.io/tigre/pen/xRbZPZ
You are using it wrong. Dont directly use sparcle plugin on html tag instead add element to starting of body tag and style it <body> <div id="bg"></div> <div>Sparkle, sparkle!</div> </body> where bg is your sparkle element you are pointing to. and Style bg element as following #bg { position:fixed; display:block; width:100%; height:100%; top:0; left:0; background: #1d1f20; overflow:hidden; z-index:-1; } Here is updated Codepen link : https://codepen.io/anon/pen/LbELWa
Trying to impletment a Slide-In Menu
im new to front end development and currently trying to implement a Slide in Sidebar-snippet into my layout. I think there is something wrong with the JS, since I have no clue about JS its hard to tell though. I know that its a lot to ask for but id appreciate some guidance. HTML: <div class="st-container"> <nav class="st-menu st-effect-1" id="menu-1"> <!-- Sidebar Menu --> <ul> <li><a class="icon icon-data" href="#">Data Management</a></li> <li><a class="icon icon-location" href="#">Location</a></li> <li><a class="icon icon-study" href="#">Study</a></li> <li><a class="icon icon-photo" href="#">Collections</a></li> <li><a class="icon icon-wallet" href="#">Credits</a></li> </ul> </nav> <!-- End of Sidebar Menü --> <div class="navigation"> <!--Navigation--> <div id="st-trigger-effects" class="section"> <button data-effect="st-effect-1"><i class="fa fa-bars"></button></i></li> <!-- Hamburger Button --> </div> <div class="nav-content section"> <div class="nav-logo">Blogger</div> <div class="nav-btn"><button class="wrt-btn">Schreib' einen Artikel</button></div> </div> <div class="nav-right section"> <ul> <li>Log In</li> <li>Register</li> </ul> </div> </div><!--End of Navigation / Header--> CSS: .navigation { width: 100%; border-bottom: solid 1px #eee; position: fixed; font-size: 14px; box-sizing: border-box; font-weight: 400; font-style: normal; line-height: 1.6; min-height: 65px; padding-top: 10px; background-color: #fff; z-index: 500; } .section, li, .nav-logo, .nav-btn { display:inline-block; } #st-trigger-effects, .nav-right { width: 21%; } .nav-content { width: 55%; } .nav-btn { text-align: right; } .nav-right { text-align: right; } .nav-logo, .nav-btn { width: 49.3%; padding: 0; margin: 0; } #st-trigger-effects button { margin-left: 35px; } /****************************************** Slide in Bar *******************************************/ .st-menu { position: absolute; top: 0; left: 0; z-index: 100; visibility: hidden; width: 300px; height: 100%; background: #48a770; -webkit-transition: all 0.5s; transition: all 0.5s; } .st-menu::after { position: absolute; top: 0; right: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.2); opacity: 1; -webkit-transition: opacity 0.5s; transition: opacity 0.5s; } .st-menu-open .st-menu::after { width: 0; height: 0; opacity: 0; -webkit-transition: opacity 0.5s, width 0.1s 0.5s, height 0.1s 0.5s; transition: opacity 0.5s, width 0.1s 0.5s, height 0.1s 0.5s; } /* content style of sidebar */ .fa.fa-bars { font-size: 1.5em; } .st-menu ul { margin: 0; padding: 0; list-style: none; } .st-menu h2 { margin: 0; padding: 1em; color: rgba(0,0,0,0.4); text-shadow: 0 0 1px rgba(0,0,0,0.1); font-weight: 300; font-size: 2em; } .st-menu ul li a { display: block; padding: 1em 1em 1em 1.2em; outline: none; box-shadow: inset 0 -1px rgba(0,0,0,0.2); color: #f3efe0; text-transform: uppercase; text-shadow: 0 0 1px rgba(255,255,255,0.1); letter-spacing: 1px; font-weight: 400; -webkit-transition: background 0.3s, box-shadow 0.3s; transition: background 0.3s, box-shadow 0.3s; } .st-menu ul li:first-child a { box-shadow: inset 0 -1px rgba(0,0,0,0.2), inset 0 1px rgba(0,0,0,0.2); } .st-menu ul li a:hover { background: rgba(0,0,0,0.2); box-shadow: inset 0 -1px rgba(0,0,0,0); color: #fff; } /* Effect 1: Slide in on top */ .st-effect-1.st-menu { visibility: visible; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } .st-effect-1.st-menu-open .st-effect-1.st-menu { visibility: visible; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .st-effect-1.st-menu::after { display: none; } Classie.js *! * classie - class helper functions * from bonzo https://github.com/ded/bonzo * * classie.has( elem, 'my-class' ) -> true/false * classie.add( elem, 'my-new-class' ) * classie.remove( elem, 'my-unwanted-class' ) * classie.toggle( elem, 'my-class' ) */ /*jshint browser: true, strict: true, undef: true */ /*global define: false */ ( function( window ) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } // classList support for class management // altho to be fair, the api sucks because it won't accept multiple classes at once var hasClass, addClass, removeClass; if ( 'classList' in document.documentElement ) { hasClass = function( elem, c ) { return elem.classList.contains( c ); }; addClass = function( elem, c ) { elem.classList.add( c ); }; removeClass = function( elem, c ) { elem.classList.remove( c ); }; } else { hasClass = function( elem, c ) { return classReg( c ).test( elem.className ); }; addClass = function( elem, c ) { if ( !hasClass( elem, c ) ) { elem.className = elem.className + ' ' + c; } }; removeClass = function( elem, c ) { elem.className = elem.className.replace( classReg( c ), ' ' ); }; } function toggleClass( elem, c ) { var fn = hasClass( elem, c ) ? removeClass : addClass; fn( elem, c ); } var classie = { // full names hasClass: hasClass, addClass: addClass, removeClass: removeClass, toggleClass: toggleClass, // short names has: hasClass, add: addClass, remove: removeClass, toggle: toggleClass }; // transport if ( typeof define === 'function' && define.amd ) { // AMD define( classie ); } else { // browser global window.classie = classie; } })( window ); Modernizer.Custom.js ;window.Modernizr=function(a,b,c){function z(a){j.cssText=a}function A(a,b){return z(m.join(a+";")+(b||""))}function B(a,b){return typeof a===b}function C(a,b){return!!~(""+a).indexOf(b)}function D(a,b){for(var d in a){var e=a[d];if(!C(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function E(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:B(f,"function")?f.bind(d||b):f}return!1}function F(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return B(b,"string")||B(b,"undefined")?D(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),E(e,b,c))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},x={}.hasOwnProperty,y;!B(x,"undefined")&&!B(x.call,"undefined")?y=function(a,b){return x.call(a,b)}:y=function(a,b){return b in a&&B(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.csstransforms3d=function(){var a=!!F("perspective");return a&&"webkitPerspective"in g.style&&w("#media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a};for(var G in q)y(q,G)&&(v=G.toLowerCase(),e[v]=q[G](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)y(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},z(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return D([a])},e.testAllProps=F,e.testStyles=w,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))}; SidebarEffects.js var SidebarMenuEffects = (function() { function hasParentClass( e, classname ) { if(e === document) return false; if( classie.has( e, classname ) ) { return true; } return e.parentNode && hasParentClass( e.parentNode, classname ); } // http://coveroverflow.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; } function init() { var container = document.getElementById( 'st-container' ), buttons = Array.prototype.slice.call( document.querySelectorAll( '#st-trigger-effects > button' ) ), // event type (if mobile use touch events) eventtype = mobilecheck() ? 'touchstart' : 'click', resetMenu = function() { classie.remove( container, 'st-menu-open' ); }, bodyClickFn = function(evt) { if( !hasParentClass( evt.target, 'st-menu' ) ) { resetMenu(); document.removeEventListener( eventtype, bodyClickFn ); } }; buttons.forEach( function( el, i ) { var effect = el.getAttribute( 'data-effect' ); el.addEventListener( eventtype, function( ev ) { ev.stopPropagation(); ev.preventDefault(); container.className = 'st-container'; // clear classie.add( container, effect ); setTimeout( function() { classie.add( container, 'st-menu-open' ); }, 25 ); document.addEventListener( eventtype, bodyClickFn ); }); } ); } init(); })(); The JS files have been called in the HTML. Again, help would be appreciated.
Okay firstly, you are trying to get an id of an element which doesn't have an id called st-container Change this: <div class="st-container"> var container = document.getElementById( 'st-container' ) Into this: <div id="st-container" class="st-container"> var container = document.getElementById( 'st-container' ) You can now use the button to make the side bar appear, this will make it appear under all your content at the moment. JSFiddle for example Update to come: Updated JSfiddle to show menu above content
Elements load with mouse scroll [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance. Closed 9 years ago. Improve this question I just want to know how I do this effect: Example: Open the website, and, when I start to scroll, the other elements appear from fade, like this: https://www.brightfunds.org/
This tutorial may be a good place for you to start: http://tympanus.net/codrops/2013/07/18/on-scroll-effect-layout/ HTML <div id="cbp-so-scroller" class="cbp-so-scroller"> <section class="cbp-so-section"> <article class="cbp-so-side cbp-so-side-left"> <h2>Lemon drops</h2> <p>Fruitcake toffee jujubes. Topping biscuit sesame snaps jelly caramels jujubes tiramisu fruitcake. Marzipan tart lemon drops chocolate sesame snaps jelly beans.</p> </article> <figure class="cbp-so-side cbp-so-side-right"> <img src="images/1.png" alt="img01"> </figure> </section> <section class="cbp-so-section"> <figure class="cbp-so-side cbp-so-side-left"> <img src="images/2.png" alt="img01"> </figure> <article class="cbp-so-side cbp-so-side-right"> <h2>Plum caramels</h2> <p>Lollipop powder danish sugar plum caramels liquorice sweet cookie. Gummi bears caramels gummi bears candy canes cheesecake sweet roll icing dragée. Gummies jelly-o tart. Cheesecake unerdwear.com candy canes apple pie halvah chocolate tiramisu.</p> </article> </section> <section> <!-- ... --> </section> <!-- ... --> </div> CSS .cbp-so-scroller { margin-top: 50px; overflow: hidden; } .cbp-so-section { margin-bottom: 15em; position: relative; } /* Clear floats of children */ .cbp-so-section:before, .cbp-so-section:after { content: " "; display: table; } .cbp-so-section:after { clear: both; } /* Text styling */ .cbp-so-section h2 { font-size: 5em; font-weight: 300; line-height: 1; } .cbp-so-section p { font-size: 2em; font-weight: 300; } /* Sides */ .cbp-so-side { width: 50%; float: left; margin: 0; padding: 3em 4%; overflow: hidden; min-height: 12em; } /* Clear floats of children */ .cbp-so-side:before, .cbp-so-side:after { content: " "; display: table; } .cbp-so-side:after { clear: both; } .cbp-so-side-right { text-align: left; } .cbp-so-side-left { text-align: right; } .cbp-so-side-right img { float: left; } .cbp-so-side-left img { float: right; } /* Initial state (hidden or anything else) */ .cbp-so-init .cbp-so-side { opacity: 0; -webkit-transition: none; -moz-transition: none; transition: none; } .cbp-so-init .cbp-so-side-left { -webkit-transform: translateX(-80px); -moz-transform: translateX(-80px); transform: translateX(-80px); } .cbp-so-init .cbp-so-side-right { -webkit-transform: translateX(80px); -moz-transform: translateX(80px); transform: translateX(80px); } /* Animated state */ /* add you final states (transition) or your effects (animations) for each side */ .cbp-so-section.cbp-so-animate .cbp-so-side-left, .cbp-so-section.cbp-so-animate .cbp-so-side-right { -webkit-transition: -webkit-transform 0.5s, opacity 0.5s; -moz-transition: -moz-transform 0.5s, opacity 0.5s; transition: transform 0.5s, opacity 0.5s; -webkit-transform: translateX(0px); -moz-transform: translateX(0px); transform: translateX(0px); opacity: 1; } /* For example, add a delay for the right side: .cbp-so-section.cbp-so-animate .cbp-so-side-right { -webkit-transition-delay: 0.2s; -moz-transition-delay: 0.2s; transition-delay: 0.2s; } */ /* Example media queries */ #media screen and (max-width: 73.5em) { .cbp-so-scroller { font-size: 65%; } .cbp-so-section h2 { margin: 0; } .cbp-so-side img { max-width: 120%; } } #media screen and (max-width: 41.125em) { .cbp-so-side { float: none; width: 100%; } .cbp-so-side img { max-width: 100%; } } Javascript /** * cbpScroller.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'; var docElem = window.document.documentElement; function getViewportH() { var client = docElem['clientHeight'], inner = window['innerHeight']; if( client < inner ) return inner; else return client; } function scrollY() { return window.pageYOffset || docElem.scrollTop; } // http://stackoverflow.com/a/5598797/989439 function getOffset( el ) { var offsetTop = 0, offsetLeft = 0; do { if ( !isNaN( el.offsetTop ) ) { offsetTop += el.offsetTop; } if ( !isNaN( el.offsetLeft ) ) { offsetLeft += el.offsetLeft; } } while( el = el.offsetParent ) return { top : offsetTop, left : offsetLeft } } function inViewport( el, h ) { var elH = el.offsetHeight, scrolled = scrollY(), viewed = scrolled + getViewportH(), elTop = getOffset(el).top, elBottom = elTop + elH, // if 0, the element is considered in the viewport as soon as it enters. // if 1, the element is considered in the viewport only when it's fully inside // value in percentage (1 >= h >= 0) h = h || 0; return (elTop + elH * h) <= viewed && (elBottom) >= scrolled; } function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } function cbpScroller( el, options ) { this.el = el; this.options = extend( this.defaults, options ); this._init(); } cbpScroller.prototype = { defaults : { // The viewportFactor defines how much of the appearing item has to be visible in order to trigger the animation // if we'd use a value of 0, this would mean that it would add the animation class as soon as the item is in the viewport. // If we were to use the value of 1, the animation would only be triggered when we see all of the item in the viewport (100% of it) viewportFactor : 0.2 }, _init : function() { if( Modernizr.touch ) return; this.sections = Array.prototype.slice.call( this.el.querySelectorAll( '.cbp-so-section' ) ); this.didScroll = false; var self = this; // the sections already shown... this.sections.forEach( function( el, i ) { if( !inViewport( el ) ) { classie.add( el, 'cbp-so-init' ); } } ); var scrollHandler = function() { if( !self.didScroll ) { self.didScroll = true; setTimeout( function() { self._scrollPage(); }, 60 ); } }, resizeHandler = function() { function delayed() { self._scrollPage(); self.resizeTimeout = null; } if ( self.resizeTimeout ) { clearTimeout( self.resizeTimeout ); } self.resizeTimeout = setTimeout( delayed, 200 ); }; window.addEventListener( 'scroll', scrollHandler, false ); window.addEventListener( 'resize', resizeHandler, false ); }, _scrollPage : function() { var self = this; this.sections.forEach( function( el, i ) { if( inViewport( el, self.options.viewportFactor ) ) { classie.add( el, 'cbp-so-animate' ); } else { // this add class init if it doesn't have it. This will ensure that the items initially in the viewport will also animate on scroll classie.add( el, 'cbp-so-init' ); classie.remove( el, 'cbp-so-animate' ); } }); this.didScroll = false; } } // add to global namespace window.cbpScroller = cbpScroller; } )( window );