Trying to impletment a Slide-In Menu - javascript
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
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.
using multiple instances of popup
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>
Font Awesome Icon doesnt get displayed?
I'm building an expanding search bar, unfortunately the search icon from Font Awesome is not showing. Here is the code: ;(function(window) { 'use strict'; // EventListener | #jon_neal | //github.com/jonathantneal/EventListener !window.addEventListener && window.Element && (function() { function addToPrototype(name, method) { Window.prototype[name] = HTMLDocument.prototype[name] = Element.prototype[name] = method; } var registry = []; addToPrototype("addEventListener", function(type, listener) { var target = this; registry.unshift({ __listener: function(event) { event.currentTarget = target; event.pageX = event.clientX + document.documentElement.scrollLeft; event.pageY = event.clientY + document.documentElement.scrollTop; event.preventDefault = function() { event.returnValue = false }; event.relatedTarget = event.fromElement || null; event.stopPropagation = function() { event.cancelBubble = true }; event.relatedTarget = event.fromElement || null; event.target = event.srcElement || target; event.timeStamp = +new Date; listener.call(target, event); }, listener: listener, target: target, type: type }); this.attachEvent("on" + type, registry[0].__listener); }); addToPrototype("removeEventListener", function(type, listener) { for (var index = 0, length = registry.length; index < length; ++index) { if (registry[index].target == this && registry[index].type == type && registry[index].listener == listener) { return this.detachEvent("on" + type, registry.splice(index, 1)[0].__listener); } } }); addToPrototype("dispatchEvent", function(eventObject) { try { return this.fireEvent("on" + eventObject.type, eventObject); } catch (error) { for (var index = 0, length = registry.length; index < length; ++index) { if (registry[index].target == this && registry[index].type == eventObject.type) { registry[index].call(this, eventObject); } } } }); })(); // http://stackoverflow.com/a/11381730/989439 function mobilecheck() { var check = false; (function(a) { if (/(android|ipad|playbook|silk|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true })(navigator.userAgent || navigator.vendor || window.opera); return check; } // http://www.jonathantneal.com/blog/polyfills-and-prototypes/ !String.prototype.trim && (String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }); function UISearch(el, options) { this.el = el; this.inputEl = el.querySelector('form > input.sb-search-input'); this._initEvents(); } UISearch.prototype = { _initEvents: function() { var self = this, initSearchFn = function(ev) { ev.stopPropagation(); // trim its value self.inputEl.value = self.inputEl.value.trim(); if (!classie.has(self.el, 'sb-search-open')) { // open it ev.preventDefault(); self.open(); } else if (classie.has(self.el, 'sb-search-open') && /^\s*$/.test(self.inputEl.value)) { // close it ev.preventDefault(); self.close(); } } this.el.addEventListener('click', initSearchFn); this.el.addEventListener('touchstart', initSearchFn); this.inputEl.addEventListener('click', function(ev) { ev.stopPropagation(); }); this.inputEl.addEventListener('touchstart', function(ev) { ev.stopPropagation(); }); }, open: function() { var self = this; classie.add(this.el, 'sb-search-open'); // focus the input if (!mobilecheck()) { this.inputEl.focus(); } // close the search input if body is clicked var bodyFn = function(ev) { self.close(); this.removeEventListener('click', bodyFn); this.removeEventListener('touchstart', bodyFn); }; document.addEventListener('click', bodyFn); document.addEventListener('touchstart', bodyFn); }, close: function() { this.inputEl.blur(); classie.remove(this.el, 'sb-search-open'); } } // add to global namespace window.UISearch = UISearch; })(window); .sb-search { float: right; position: relative; margin-top: 10px; width: 0%; min-width: 40px; height: 40px; overflow: hidden; -webkit-transition: width 0.3s; -moz-transition: width 0.3s; transition: width 0.3s; -webkit-backface-visibility: hidden; } .sb-search-input { position: absolute; top: 0; right: 0; border: none; outline: none; background: #fff; width: 100%; height: 40px; margin: 0; z-index: 10; padding: 20px 65px 20px 20px; font-family: inherit; font-size: 20px; color: #2c3e50; } .sb-search-input::-webkit-input-placeholder { color: #efb480; } .sb-search-input:-moz-placeholder { color: #efb480; } .sb-search-input::-moz-placeholder { color: #efb480; } .sb-search-input:-ms-input-placeholder { color: #efb480; } .fa.fa-search, .sb-search-submit { width: 40px; height: 40px; display: block; position: absolute; right: 0; top: 0; padding: 0; margin: 0; line-height: 60px; text-align: center; cursor: pointer; } .sb-search-submit { background: #fff; /* IE needs this */ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* IE 8 */ filter: alpha(opacity=0); /* IE 5-7 */ opacity: 0; color: transparent; border: none; outline: none; z-index: -1; } .fa.fa-search { border: none; font-size: 22px; background: #efb480; z-index: 90; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; -webkit-font-smoothing: antialiased; } .fa.fa-search:before { content: "\e000"; } /* Open state */ .sb-search.sb-search-open, .no-js .sb-search { width: 100%; } .sb-search.sb-search-open .fa.fa-search, .no-js .sb-search .fa.fa-search { background: #da6d0d; color: #fff; z-index: 11; } .sb-search.sb-search-open .sb-search-submit, .no-js .sb-search .sb-search-submit { z-index: 90; } <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/> <div class="nav-btn"> <div id="sb-search" class="sb-search"> <form> <input class="sb-search-input" placeholder="Enter your search term..." type="text" value="" name="search" id="search" /> <input class="sb-search-submit" type="submit" value="" /> <button class="sb-icon-search"><i class="fa fa-search"></i> </button> </form> </div> </div> I only started front-end development a few weeks ago and I'd appreciate some help! :) I included the font-awesome.min.css stylesheet. Its working in other lines. Here is the jsfiddle: https://jsfiddle.net/0wm440gn/4/ The JS works fine in my files, I don't understand why JSFiddle doesn't do it properly. But my problem must be somewhere in the Markup/CSS.
Your problem is on line 88 of your CSS file, where it says: .fa.fa-search:before { content: "\e000"; } That's not the correct unicode character, and if you're using fontawesome you don't need it anyway. Delete those lines and fontawesome will take care of you.
Just include the external reference to Fontawesome: https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css and remove the lines .fa.fa-search:before { content: "\e000"; } JSFiddle demo
Your problem is in your CSS. You have the following rule: .fa.fa-search:before { content: "\e000"; } In the font-awesome.css file, .fa-search is defined as: .fa-search:before { content: "\f002"; } Since your selector, in your CSS, has a higher specificity, the default value of \F002 is being replaced with \E000. I removed this and the glyph appeared correctly. Broken .fa.fa-search:before { content: "\e000"; } <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" /> <button class="sb-icon-search"><i class="fa fa-search"></i> Fixed <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/> <button class="sb-icon-search"><i class="fa fa-search"></i>
Same jquery plugin in same url only working one
I'm a very-very beginner in jQuery and JavaScript. Basically I'm about to create custom responsive menu with 2 navigation on the right and the left side, the first one is working fine, but not with the other one. The script i took from (http://tympanus.net/codrops/2013/04/19/responsive-multi-level-menu/) . My script is look like this (codepen.io/donlego/full/xGjzWR). HTML <body> <div id="dl-menu" class="dl-menuwrapper"><!-- Codrops top bar --> <button class="dl-trigger">Open Menu</button> <ul class="dl-menu"> <li> Fashion <ul class="dl-submenu"> <li> Men </li> <li> Women <ul class="dl-submenu"> <li>Jackets</li> <li>Knits</li> <li>Jeans</li> <li>Dresses</li> <li>Blouses</li> <li>T-Shirts</li> <li>Underwear</li> </ul> </li> <li> Children <ul class="dl-submenu"> <li>Boys</li> <li>Girls</li> </ul> </li> </ul> </li> <li> Electronics <ul class="dl-submenu"> <li>Camera & Photo</li> <li>TV & Home Cinema</li> <li>Phones</li> <li>PC & Video Games</li> </ul> </li> <li> Furniture <ul class="dl-submenu"> <li> Living Room <ul class="dl-submenu"> <li>Sofas & Loveseats</li> <li>Coffee & Accent Tables</li> <li>Chairs & Recliners</li> <li>Bookshelves</li> </ul> </li> <li> Bedroom <ul class="dl-submenu"> <li> Beds <ul class="dl-submenu"> <li>Upholstered Beds</li> <li>Divans</li> <li>Metal Beds</li> <li>Storage Beds</li> <li>Wooden Beds</li> <li>Children's Beds</li> </ul> </li> <li>Bedroom Sets</li> <li>Chests & Dressers</li> </ul> </li> <li>Home Office</li> <li>Dining & Bar</li> <li>Patio</li> </ul> </li> <li> Jewelry & Watches <ul class="dl-submenu"> <li>Fine Jewelry</li> <li>Fashion Jewelry</li> <li>Watches</li> <li> Wedding Jewelry <ul class="dl-submenu"> <li>Engagement Rings</li> <li>Bridal Sets</li> <li>Women's Wedding Bands</li> <li>Men's Wedding Bands</li> </ul> </li> </ul> </li> </ul> </div><!-- /dl-menuwrapper --> <div class="clearfix"></div> <div id="dl-menu" class="dl-menuwrapper"><!-- Codrops top bar --> <button class="dl-trigger">Open Menu</button> <ul class="dl-menu"> <li> Fashion <ul class="dl-submenu"> <li> Men <ul class="dl-submenu"> <li>Shirts</li> <li>Jackets</li> <li>Chinos & Trousers</li> <li>Jeans</li> <li>T-Shirts</li> <li>Underwear</li> </ul> </li> <li> Women <ul class="dl-submenu"> <li>Jackets</li> <li>Knits</li> <li>Jeans</li> <li>Dresses</li> <li>Blouses</li> <li>T-Shirts</li> <li>Underwear</li> </ul> </li> <li> Children <ul class="dl-submenu"> <li>Boys</li> <li>Girls</li> </ul> </li> </ul> </li> <li> Electronics <ul class="dl-submenu"> <li>Camera & Photo</li> <li>TV & Home Cinema</li> <li>Phones</li> <li>PC & Video Games</li> </ul> </li> <li> Furniture <ul class="dl-submenu"> <li> Living Room <ul class="dl-submenu"> <li>Sofas & Loveseats</li> <li>Coffee & Accent Tables</li> <li>Chairs & Recliners</li> <li>Bookshelves</li> </ul> </li> <li> Bedroom <ul class="dl-submenu"> <li> Beds <ul class="dl-submenu"> <li>Upholstered Beds</li> <li>Divans</li> <li>Metal Beds</li> <li>Storage Beds</li> <li>Wooden Beds</li> <li>Children's Beds</li> </ul> </li> <li>Bedroom Sets</li> <li>Chests & Dressers</li> </ul> </li> <li>Home Office</li> <li>Dining & Bar</li> <li>Patio</li> </ul> </li> <li> Jewelry & Watches <ul class="dl-submenu"> <li>Fine Jewelry</li> <li>Fashion Jewelry</li> <li>Watches</li> <li> Wedding Jewelry <ul class="dl-submenu"> <li>Engagement Rings</li> <li>Bridal Sets</li> <li>Women's Wedding Bands</li> <li>Men's Wedding Bands</li> </ul> </li> </ul> </li> </ul> </div><!-- /dl-menuwrapper --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function() { $( '#dl-menu' ).dlmenu(); }); </script> </body> CSS #font-face { font-family: 'icomoon'; src:url('../fonts/icomoon.eot'); src:url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'), url('../fonts/icomoon.woff') format('woff'), url('../fonts/icomoon.ttf') format('truetype'), url('../fonts/icomoon.svg#icomoon') format('svg'); font-weight: normal; font-style: normal; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } /* Common styles of menus */ .dl-menuwrapper { width: 0; max-width: 90%; float: left; position: relative; -webkit-perspective: 1000px; perspective: 1000px; -webkit-perspective-origin: 50% 200%; perspective-origin: 50% 200%; } .dl-menuwrapper:first-child { margin-right: 0; } .dl-menuwrapper button { background: #395066; border: none; width: 48px; height: 90px; text-indent: -900em; overflow: hidden; position: relative; cursor: pointer; outline: none; -webkit-box-shadow:inset 0 -2px rgba(255,255,255,0.1),inset 0 -3px rgba(0,0,0,0.1),0 1px rgba(0,0,0,0.05); -moz-box-shadow:inset 0 -2px rgba(255,255,255,0.1),inset 0 -3px rgba(0,0,0,0.1),0 1px rgba(0,0,0,0.05); box-shadow:inset 0 -2px rgba(255,255,255,0.1),inset 0 -3px rgba(0,0,0,0.1),0 1px rgba(0,0,0,0.05); } .dl-menuwrapper button:hover, .dl-menuwrapper button.dl-active, .dl-menuwrapper ul { background: #32475b; } .dl-menuwrapper button:after { content: ''; position: absolute; width: 68%; height: 5px; background: #fff; top: 30px; left: 16%; box-shadow: 0 10px 0 #fff, 0 20px 0 #fff; } .dl-menuwrapper ul { padding: 0; list-style: none; -webkit-transform-style: preserve-3d; transform-style: preserve-3d; background-color: #009ee8; width: 350px; } .dl-menuwrapper li { position: relative; width: 350px; background-color: #395066; } .dl-menuwrapper li a { display: block; position: relative; padding: 15px 20px; font-size: 16px; line-height: 20px; font-weight: 300; color: #fff; outline: none; background-color: #395066; } .no-touch .dl-menuwrapper li a:hover { background: rgba(0,0,0,0.2); } .dl-menuwrapper li.dl-back > a { padding-left: 30px; background: #163a5b; } .dl-menuwrapper li.dl-back:after, .dl-menuwrapper li > a:not(:only-child):after { position: absolute; top: 0; line-height: 50px; font-family: 'icomoon'; speak: none; -webkit-font-smoothing: antialiased; content: "\e000"; color: #eeeeee; } .dl-menuwrapper li.dl-back:after { left: 10px; color: rgba(212,204,198,0.3); -webkit-transform: rotate(180deg); transform: rotate(180deg); color: #eeeeee; } .dl-menuwrapper li > a:after { right: 10px; color: rgba(0,0,0,0.15); } .dl-menuwrapper .dl-menu { /* biyang kerok 2*/ position: absolute; width: 100%; opacity: 0; pointer-events: none; -webkit-transform: translateY(10px); transform: translateY(10px); -webkit-backface-visibility: hidden; backface-visibility: hidden; } .dl-menuwrapper .dl-menu.dl-menu-toggle { transition: all 0.3s ease; } .dl-menuwrapper .dl-menu.dl-menuopen { opacity: 1; pointer-events: auto; -webkit-transform: translateY(0px); transform: translateY(0px); } /* Hide the inner submenus */ .dl-menuwrapper li .dl-submenu { display: none; } /* When a submenu is openend, we will hide all li siblings. For that we give a class to the parent menu called "dl-subview". We also hide the submenu link. The opened submenu will get the class "dl-subviewopen". All this is done for any sub-level being entered. */ .dl-menu.dl-subview li, .dl-menu.dl-subview li.dl-subviewopen > a, .dl-menu.dl-subview li.dl-subview > a { display: none; } .dl-menu.dl-subview li.dl-subview, .dl-menu.dl-subview li.dl-subview .dl-submenu, .dl-menu.dl-subview li.dl-subviewopen, .dl-menu.dl-subview li.dl-subviewopen > .dl-submenu, .dl-menu.dl-subview li.dl-subviewopen > .dl-submenu > li { display: block; } Jquery ;( function( $, window, undefined ) { 'use strict'; // global var Modernizr = window.Modernizr, $body = $( 'body' ); $.DLMenu = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.DLMenu.defaults = { // classes for the animation effects animationClasses : { classin : 'dl-animate-in-1', classout : 'dl-animate-out-1' }, // callback: click a link that has a sub menu // el is the link element (li); name is the level name onLevelClick : function( el, name ) { return false; }, // callback: click a link that does not have a sub menu // el is the link element (li); ev is the event obj onLinkClick : function( el, ev ) { return false; } }; $.DLMenu.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.DLMenu.defaults, options ); // cache some elements and initialize some variables this._config(); var animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' }, transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'msTransition' : 'MSTransitionEnd', 'transition' : 'transitionend' }; // animation end event name this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu'; // transition end event name this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu', // support for css animations and css transitions this.supportAnimations = Modernizr.cssanimations, this.supportTransitions = Modernizr.csstransitions; this._initEvents(); }, _config : function() { this.open = false; this.$trigger = this.$el.children( '.dl-trigger' ); this.$menu = this.$el.children( 'ul.dl-menu' ); this.$menuitems = this.$menu.find( 'li:not(.dl-back)' ); this.$el.find( 'ul.dl-submenu' ).prepend( '<li class="dl-back">back</li>' ); this.$back = this.$menu.find( 'li.dl-back' ); }, _initEvents : function() { var self = this; this.$trigger.on( 'click.dlmenu', function() { if( self.open ) { self._closeMenu(); } else { self._openMenu(); } return false; } ); this.$menuitems.on( 'click.dlmenu', function( event ) { event.stopPropagation(); var $item = $(this), $submenu = $item.children( 'ul.dl-submenu' ); if( $submenu.length > 0 ) { var $flyin = $submenu.clone().css( 'opacity', 0 ).insertAfter( self.$menu ), onAnimationEndFn = function() { self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' ); $item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' ); $flyin.remove(); }; setTimeout( function() { $flyin.addClass( self.options.animationClasses.classin ); self.$menu.addClass( self.options.animationClasses.classout ); if( self.supportAnimations ) { self.$menu.on( self.animEndEventName, onAnimationEndFn ); } else { onAnimationEndFn.call(); } self.options.onLevelClick( $item, $item.children( 'a:first' ).text() ); } ); return false; } else { self.options.onLinkClick( $item, event ); } } ); this.$back.on( 'click.dlmenu', function( event ) { var $this = $( this ), $submenu = $this.parents( 'ul.dl-submenu:first' ), $item = $submenu.parent(), $flyin = $submenu.clone().insertAfter( self.$menu ); var onAnimationEndFn = function() { self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin ); $flyin.remove(); }; setTimeout( function() { $flyin.addClass( self.options.animationClasses.classout ); self.$menu.addClass( self.options.animationClasses.classin ); if( self.supportAnimations ) { self.$menu.on( self.animEndEventName, onAnimationEndFn ); } else { onAnimationEndFn.call(); } $item.removeClass( 'dl-subviewopen' ); var $subview = $this.parents( '.dl-subview:first' ); if( $subview.is( 'li' ) ) { $subview.addClass( 'dl-subviewopen' ); } $subview.removeClass( 'dl-subview' ); } ); return false; } ); }, closeMenu : function() { if( this.open ) { this._closeMenu(); } }, _closeMenu : function() { var self = this, onTransitionEndFn = function() { self.$menu.off( self.transEndEventName ); self._resetMenu(); }; this.$menu.removeClass( 'dl-menuopen' ); this.$menu.addClass( 'dl-menu-toggle' ); this.$trigger.removeClass( 'dl-active' ); if( this.supportTransitions ) { this.$menu.on( this.transEndEventName, onTransitionEndFn ); } else { onTransitionEndFn.call(); } this.open = false; }, openMenu : function() { if( !this.open ) { this._openMenu(); } }, _openMenu : function() { var self = this; // clicking somewhere else makes the menu close $body.off( 'click' ).on( 'click.dlmenu', function() { self._closeMenu() ; } ); this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() { $( this ).removeClass( 'dl-menu-toggle' ); } ); this.$trigger.addClass( 'dl-active' ); this.open = true; }, // resets the menu to its original state (first level of options) _resetMenu : function() { this.$menu.removeClass( 'dl-subview' ); this.$menuitems.removeClass( 'dl-subview dl-subviewopen' ); } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.dlmenu = function( options ) { if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { var instance = $.data( this, 'dlmenu' ); if ( !instance ) { logError( "cannot call methods on dlmenu prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for dlmenu instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'dlmenu' ); if ( instance ) { instance._init(); } else { instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) ); } }); } return this; }; $.fn.DLMenu=function(){ return this.each( function(){ if ( $( this ).data( 'dlmenu' ) ){ return false; } $( this ).data( 'dlmenu', true ); // plugin code }); }; } )( jQuery, window );
Two elements on the same page cannot share the same ID. Change $( '#dl-menu' ).dlmenu(); to $( '.dl-menuwrapper' ).dlmenu(); and it will most likely work. Reference: https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really
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 );