Uncaught ReferenceError:JQuery is not defined - javascript

I am learning how to create single page apps from a book called Single Page Web Applications. I have tried the code provided just to build my first simple SPA, but when I launch it the slider isn't working and using developer tools in the browser gives the message "Uncaught ReferenceError: JQuery is not defined". Why does the error happen? The following is the code as it is written in the book. The problem is toward the bottom where I have arrows pointing.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>SPA Chapter 1 section 1.2.2</title>
<style type="text/css">
body {
width : 100%;
height : 100%;
overflow : hidden;
background-color : #777;
}
#spa {
position : absolute;
top : 8px;
left : 8px;
bottom : 8px;
right : 8px;
border-radius : 8px 8px 0 8px;
background-color : #fff;
}
.spa-slider {
position : absolute;
bottom : 0;
right : 2px;
width : 300px;
height : 16px;
cursor : pointer;
border-radius : 8px 0 0 0;
background-color : #F00;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var $ = jQuery
/*jslint browser : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars : true,
white : true
*/
/*global jQuery */
// Module /spa/
// Provides chat slider capability
//
var spa = (function ( $ ) {
// Module scope variables
var
// Set constants
configMap = {
extended_height : 434,
extended_title : 'Click to retract',
retracted_height : 16,
retracted_title : 'Click to extend',
template_html : '<div class ="spa-slider"><\/div>'
},
// Declare all other module scope variables
$chatSlider,
toggleSlider, onClickSlider, initModule;
// DOM method /toggleSlider/
// alternates slider height
//
toggleSlider = function () {
var
slider_height = $chatSlider.height();
// extend slider if fully retracted
if ( slider_height === configMap.retracted_height ) {
$chatSlider
.animate({ height : configMap.extended_height })
.attr( 'title', configMap.extended_title );
return true;
}
// retract slider if fully extended
else if ( slider_height === configMap.extended_height ) {
$chatSlider
.animate({ height : configMap.retracted_height })
.attr( 'title', configMap.retracted_title );
return true;
}
// do not take action if slider is in transition
return false;
};
// Event handler /onClickSlider/
// receives click event and calls toggleSlider
//
onClickSlider = function ( event ) {
toggleSlider();
return false;
};
// Public method /initModule/
// sets initial state and provides feature
//
initModule = function ( $container ) {
// render HTML
$container.html( configMap.template_html );
$chatSlider = $container.find( '.spa-slider' );
// initialize slider height and title
// bind the user click event to the event handler
$chatSlider
.attr( 'title', configMap.retracted_title )
.click( onClickSlider );
return true;
};
return { initModule : initModule }; // <<<<<<<-------
}( JQuery )); // <<<<<<<--------
// Start SPA once DOM is ready
//
jQuery(document).ready(
function () { spa.initModule( jQuery('#spa') ); }
);
</script>
</head>
<body>
<div id="spa">
<div class="spa-slider"></div>
</div>
</body>
</html>

JavaScript is case sensitive. On the second line you marked with an arrow, change JQuery to jQuery (with a lowercase j):
}( jQuery ));<<<<<<<--------

Seems like the Jquery script source you're using may be outdated. Try this one:
'<script src="http://code.jquery.com/jquery-latest.min.js"></script>'

Related

add image in javascript

I'm using a WordPress plugin (open source) that will allow you to add an expandable widget for a WooCommerce product category.
This is the JS:
// mtree.js
// Requires jquery.js and velocity.js (optional but recommended).
// Copy the below function, add to your JS, and simply add a list <ul class=mtree> ... </ul>
;(function ($, window, document, undefined) {
// Only apply if mtree list exists
if($('ul.mtree').length) {
// Settings
var collapsed = true; // Start with collapsed menu (only level 1 items visible)
var close_same_level = true; // Close elements on same level when opening new node.
var duration = mtree_options.duration; // Animation duration should be tweaked according to easing.
var listAnim = true; // Animate separate list items on open/close element (velocity.js only).
var easing = mtree_options.easing_type; // Velocity.js only, defaults to 'swing' with jquery animation.
// Set initial styles
$('.mtree ul').css({'overflow':'hidden', 'height': (collapsed) ? 0 : 'auto', 'display': (collapsed) ? 'none' : 'block' });
// Get node elements, and add classes for styling
var node = $('.mtree li:has(ul)');
node.each(function(index, val) {
$(this).children(':first-child').css('cursor', 'pointer')
$(this).addClass('mtree-node mtree-' + ((collapsed) ? 'closed' : 'open'));
$(this).children('ul').addClass('mtree-level-' + ($(this).parentsUntil($('ul.mtree'), 'ul').length + 1));
});
// Set mtree-active class on list items for last opened element
$('.mtree li > *:first-child').on('click.mtree-active', function(e){
if($(this).parent().hasClass('mtree-closed')) {
$('.mtree-active').not($(this).parent()).removeClass('mtree-active');
$(this).parent().addClass('mtree-active');
} else if($(this).parent().hasClass('mtree-open')){
$(this).parent().removeClass('mtree-active');
} else {
$('.mtree-active').not($(this).parent()).removeClass('mtree-active');
$(this).parent().toggleClass('mtree-active');
}
});
// Set node click elements, preferably <a> but node links can be <span> also
node.children(':first-child').on('click.mtree', function(e){
// element vars
var el = $(this).parent().children('ul').first();
var isOpen = $(this).parent().hasClass('mtree-open');
// close other elements on same level if opening
if((close_same_level || $('.csl').hasClass('active')) && !isOpen) {
var close_items = $(this).closest('ul').children('.mtree-open').not($(this).parent()).children('ul');
// Velocity.js
if($.Velocity) {
close_items.velocity({
height: 0
}, {
duration: duration,
easing: easing,
display: 'none',
delay: 100,
complete: function(){
setNodeClass($(this).parent(), true)
}
});
// jQuery fallback
} else {
close_items.delay(100).slideToggle(duration, function(){
setNodeClass($(this).parent(), true);
});
}
}
// force auto height of element so actual height can be extracted
el.css({'height': 'auto'});
// listAnim: animate child elements when opening
if(!isOpen && $.Velocity && listAnim) el.find(' > li, li.mtree-open > ul > li').css({'opacity':0}).velocity('stop').velocity('list');
// Velocity.js animate element
if($.Velocity) {
el.velocity('stop').velocity({
//translateZ: 0, // optional hardware-acceleration is automatic on mobile
height: isOpen ? [0, el.outerHeight()] : [el.outerHeight(), 0]
},{
queue: false,
duration: duration,
easing: easing,
display: isOpen ? 'none' : 'block',
begin: setNodeClass($(this).parent(), isOpen),
complete: function(){
if(!isOpen) $(this).css('height', 'auto');
}
});
// jQuery fallback animate element
} else {
setNodeClass($(this).parent(), isOpen);
el.slideToggle(duration);
}
// We can't have nodes as links unfortunately
e.preventDefault();
});
// Function for updating node class
function setNodeClass(el, isOpen) {
if(isOpen) {
el.removeClass('mtree-open').addClass('mtree-closed');
} else {
el.removeClass('mtree-closed').addClass('mtree-open');
}
}
// List animation sequence
if($.Velocity && listAnim) {
$.Velocity.Sequences.list = function (element, options, index, size) {
$.Velocity.animate(element, {
opacity: [1,0],
translateY: [0, -(index+1)]
}, {
delay: index*(duration/size/2),
duration: duration,
easing: easing
});
};
}
// Fade in mtree after classes are added.
// Useful if you have set collapsed = true or applied styles that change the structure so the menu doesn't jump between states after the function executes.
if($('.mtree').css('opacity') == 0) {
if($.Velocity) {
$('.mtree').css('opacity', 1).children().css('opacity', 0).velocity('list');
} else {
$('.mtree').show(200);
}
}
}
}(jQuery, this, this.document));
I've added a background image using CSS and :before but the image is not clickable.
Is there a way to add it on the JS so that it can be clicked as well?
I've tried to see where to add some code but actually I'm clueless, should it be between lines 29 and 37?
You can see it in: https://tester.medicalfa.gr/test/katastima/
Ok I fixed it via css, the arrows now appears like they are clickable.
The solution is to remove the code I had added:
ul.mtree.default li.mtree-open:before {
display: inline-block;
margin-left: 200px;
background: url("../images/arrow-down.svg") no-repeat center center;
background-size: 20px 20px;
}
I removed the :before as it adds the arrow behind the text and now appears after the text as it's supposed to.
The code looks like this now:
ul.mtree.default li.mtree-open {
display: block ;
background: url("../images/arrow-down.svg") no-repeat center center;
background-size: 15px 15px;
background-position:top right;
}

In flickity, how can I use arrowkeys without leftclick or tab?

this is Flickity
I cannot express in English clearly, so if possible please help editing my question.
This is my web page
https://codepen.io/haozun/pen/ywNjvQ
When I open this page, I cannot use arrowkey to navigate different carousel-cell.
I can only use arrowkey after I have mouse clicking on that page.
How can I edit the code so that I can use arrowkey at the very beginning without click on it? i.e. I open this page in my browser, and then I can use arrowkey(37,39) to rotate it immediately. I want to use the keyboardHandlers once I open the page
Flickity.keyboardHandlers = {
// left arrow
37: function() {
var leftMethod = this.options.rightToLeft ? 'next' : 'previous';
this.uiChange();
this[ leftMethod ]();
},
// right arrow
39: function() {
var rightMethod = this.options.rightToLeft ? 'previous' : 'next';
this.uiChange();
this[ rightMethod ]();
},
};
I can edit all source code, including flickity.pkgd.min.js. And my page only contains one flickity.
The official site tells we must use tab (or leftclick) first, then we can really use arrowkeys to change cells.
It almost impossible someone-else will answer this question, And the former answerer has rejected my edit, so I have to answer myself.
Adding this to JS
document.addEventListener("DOMContentLoaded", function() {
init();
});
function init() {
let flkty = new Flickity(".carousel");
flkty.focus()
}
You need to create a new Flickity instance when your app initializes, then call next() on it. You can see in the demo below that as soon as you load your app, it will scroll to the next item in the carousel:
let flkty;
const delayMs = 1000;
document.addEventListener("DOMContentLoaded", function() {
init(true);
});
function init(shouldAutoScroll) {
flkty = new Flickity(".carousel");
if (shouldAutoScroll) {
//Start an carousel auto scroll
autoScroll();
} else {
//Just flip to next item and that's it..
flkty.next();
}
}
function autoScroll() {
if (flkty) {
setInterval(function() {
flkty.next();
}, delayMs);
}
}
.carousel-cell {
min-height: 30em;
padding: 1em;
margin: 0 3em 0 3em;
width: calc( 100vw - 9em);
max-width: 40em;
box-shadow: 0px 16px 20px 5px #7777;
}
<head>
<link rel="stylesheet" href="https://unpkg.com/flickity#2/dist/flickity.min.css">
</head>
<body>
<div class="carousel" id="main" data-flickity='{
"cellAlign": "center",
"contain": true,
"adaptiveHeight":true,
"freeScroll": false,
"accessibility":true,
"wrapAround": true,
"setGallerySize":true,
"hash":true,
"selectedAttraction": 0.05,
"friction": 0.3,
"prevNextButtons":false
}'>
<div class="carousel-cell" id="carousel-cell1">1LONGLONGLONGLONG</div>
<div class="carousel-cell" id="carousel-cell2">2LONGLONGLONGLONG</div>
<div class="carousel-cell" id="carousel-cell3">3LONGLONGLONGLONG</div>
</div>
<script src="https://unpkg.com/flickity#2/dist/flickity.pkgd.min.js"></script>
</body>

jQuery click event stop working in plugin

I've been trying to add event listeners as a part of a plugin. The idea is really simple, the goal is to do a slider plugin that handles 2 dimensions (horizontally and vertically)
So I have something like this
<div class="tab-container bg-dark-blue" start-tab="Home">
<div class="tab-page" x-index="1" y-index="1" id="Home">
<h1>x=1, y=1</h1>
</div>
<div class="tab-page" x-index="1" y-index="2">
<h1>x=1, y=2</h1>
</div>
<div class="tab-page" x-index="2" y-index="1">
<h1>x=2, y=1</h1>
</div>
<div class="tab-page" x-index="2" y-index="2">
<h1>x=2, y=2</h1>
</div>
</div>
Where tab-page divs are absolutely positioned with 100% width and height, and tab-container is relatively positioned with 100% width and height of the browser.
var __MyMethods = {
width : 0
height : 0,
container : null,
// other stuff
setup : function(tab_container) {
// setup __MyPlugin.container = tab_container
// setup width, height of the container
},
/*
* Movement functions
*
*/
move : function(direction)
{
if( direction == 'left' )
{
__MyMethods.x--;
__MyMethods.translate( 'left', __MyMethods.width );
//
}
if( direction == 'right' )
{
__MyMethods.x++;
__MyMethods.translate( 'left', (-1)*__MyMethods.width );
//
}
if( direction == 'up' )
{
__MyMethods.y--;
__MyMethods.translate( 'top', __MyMethods.height );
}
if( direction == 'down' )
{
//
__MyMethods.y++;
__MyMethods.translate( 'top', (-1)*__MyMethods.height );
//
}
},
translate : function(property, offset)
{
// For each .tab-page in we animate the CSS property
$(__MyMethods.container).children(".tab-page").each( function() {
var animation = {};
var x = parseInt( $(this).css(property).replace('px','') ) + offset;
animation[property] = x.toString() + 'px';
$(this).animate(
animation,
{
'duration' : 0,
'queue' : false,
}
);
});
},
};
$.fn.MyPlugin = function()
{
__MyMethods.setup(this);
$(".btn").click( function(event)
{
__MyMethods.move( $(this).attr("move") );
console.log(this);
});
return this;
};
So I put
<button class="btn" move="up"></button>
<button class="btn" move="down"></button>
<button class="btn" move="left"></button>
<button class="btn" move="right"></button>
Somewhere in the HTML and it works fine for up, left, right... but if you click the move="down" button it works only the first time.
I don't know why is that hapening, the event never fires again if you click that button, I tried doing console.log(this) inside the click event function, but it doesn't show anything after the down button is clicked...
Any idea of what can be happening?
Thank you very much for any help you can give me
Edit: Here is a demo
Regards
In you jsfiddle the down button seems to stay behind the tab-page s. Giving z-index to menu and tab-page elements solves the problem.
In your css file:
Add
z-index: 10;
to .menu
Add
z-index: 1;
to .tab-page
css

How can I change this JS to make it visible?

_createInput: function(){
var self = this;
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
if(this._settings.multiple) input.setAttribute('multiple', 'multiple');
addStyles(input, {
'position' : 'absolute',
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
'right' : 0,
'margin' : 0,
'padding' : 0,
'fontSize' : '480px',
// in Firefox if font-family is set to
// 'inherit' the input doesn't work
'fontFamily' : 'sans-serif',
'cursor' : 'pointer'
});
var div = document.createElement("div")
div.className = 'tooltip';
div.id = 'ajaxupload-div';
div.title = 'Attach a picture';
addStyles(div, {
'display' : 'block',
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
// Make sure browse button is in the right side
// in Internet Explorer
'direction' : 'ltr',
//Max zIndex supported by Opera 9.0-9.2
'zIndex': 2147483583
});
// Make sure that element opacity exists.
// Otherwise use IE filter
if ( div.style.opacity !== "0") {
if (typeof(div.filters) == 'undefined'){
throw new Error('Opacity not supported by the browser');
}
div.style.filter = "alpha(opacity=0)";
}
addEvent(input, 'change', function(){
if ( ! input || input.value === ''){
return;
}
// Get filename from input, required
// as some browsers have path instead of it
var file = fileFromPath(input.value);
if (false === self._settings.onChange.call(self, file, getExt(file))){
self._clearInput();
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit) {
self.submit();
}
});
addEvent(input, 'mouseover', function(){
addClass(self._button, self._settings.hoverClass);
});
addEvent(input, 'mouseout', function(){
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden';
}
});
addEvent(input, 'focus', function(){
addClass(self._button, self._settings.focusClass);
});
addEvent(input, 'blur', function(){
removeClass(self._button, self._settings.focusClass);
});
div.appendChild(input);
document.body.appendChild(div);
this._input = input;
},
This JS starting at var div = document.createElement("div") produces this div tag:
<div style="display: block; position: absolute; overflow: hidden; margin: 0pt; padding: 0pt; opacity: 0; direction: ltr; z-index: 2147483583; left: 102px; top: 323.5px; width: 102px; height: 28px; visibility: hidden;">
I see where all the other attributes get changed, but how the heck can I change 'visibility: hidden;" ???
It's making me crazy please help.
Find the below section in your code i have star commented where you can modify:
addStyles(div, {
'display' : 'block', /*You cane set display none here to hide the div.*/
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
// Make sure browse button is in the right side
// in Internet Explorer
'direction' : 'ltr',
//Max zIndex supported by Opera 9.0-9.2
'zIndex': 2147483583,
'visibility':'hidden' /* If you don't set display none , you can set your style attribute you want to change like visibility here also */
});
Ok, to make it visible find the below code and try setting visibility there:
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden'; /* try setting visibility='visible' here */
}
If that doesn't work then check if any css is overriding the style property of the div by inspecting the div in your browser.
if jQuery is an option, I know there's the command $('#div').css('attribute','value');
visibility hidden is set when you "mouseout" off that input
addEvent(input, 'mouseout', function(){
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden';
}
});
you can either remove that event binding or change the statement to input.parentNode.style.visibility = 'visible';

How to display a message on screen without refreshing like SO does? [duplicate]

This is the first time I visited stack overflow and I saw a beautiful header message which displays a text and a close button.
The header bar is fixed one and is great to get the attention of the visitor. I was wondering if anyone of you guys know the code to get the same kind of header bar.
Quick pure JavaScript implementation:
function MessageBar() {
// CSS styling:
var css = function(el,s) {
for (var i in s) {
el.style[i] = s[i];
}
return el;
},
// Create the element:
bar = css(document.createElement('div'), {
top: 0,
left: 0,
position: 'fixed',
background: 'orange',
width: '100%',
padding: '10px',
textAlign: 'center'
});
// Inject it:
document.body.appendChild(bar);
// Provide a way to set the message:
this.setMessage = function(message) {
// Clear contents:
while(bar.firstChild) {
bar.removeChild(bar.firstChild);
}
// Append new message:
bar.appendChild(document.createTextNode(message));
};
// Provide a way to toggle visibility:
this.toggleVisibility = function() {
bar.style.display = bar.style.display === 'none' ? 'block' : 'none';
};
}
How to use it:
var myMessageBar = new MessageBar();
myMessageBar.setMessage('hello');
// Toggling visibility is simple:
myMessageBar.toggleVisibility();
Update:
Check out the DEMO
Code Used:
$(function(){
$('#smsg_link').click(function(){
showMessage('#9BED87', 'black', 'This is sample success message');
return false;
});
$('#imsg_link').click(function(){
showMessage('#FFE16B', 'black', 'This is sample info message');
return false;
});
$('#emsg_link').click(function(){
showMessage('#ED869B', 'black', 'This is sample error message');
return false;
});
});
/*
showMessage function by Sarfraz:
-------------------------
Shows fancy message on top of the window
params:
- bgcolor: The background color for the message box
- color: The text color of the message box
- msg: The message text
*/
var interval = null;
function showMessage(bgcolor, color, msg)
{
$('#smsg').remove();
clearInterval(interval);
if (!$('#smsg').is(':visible'))
{
if (!$('#smsg').length)
{
$('<div id="smsg">'+msg+'</div>').appendTo($('body')).css({
position:'fixed',
top:0,
left:0,
width:'98%',
height:'30px',
lineHeight:'30px',
background:bgcolor,
color:color,
zIndex:1000,
padding:'10px',
fontWeight:'bold',
fontSize:'18px',
textAlign:'center',
opacity:0.8,
margin:'auto',
display:'none'
}).slideDown('show');
interval = setTimeout(function(){
$('#smsg').animate({'width':'hide'}, function(){
$('#smsg').remove();
});
}, 3000);
}
}
}
If you want to create your own, check out the slideToggle function of jQuery.
The relevant css would include:
position: fixed;
top: 0;
width: 100%;
More information about position:fixed:
An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)
If IE6 support is important to you, you may wish to research workarounds.
Here is an alternative method using jQuery which would also slide up/down on show/hide.
Add the following HTML right after the <body> tag in your page:
<div id="msgBox">
<span id="msgText">My Message</span>
<a id="msgCloseButton" href='#'>close</a>
</div>
Add this CSS to your stylesheet
#msgBox {
padding:10px;
background-color:Orange;
text-align:center;
display:none;
font:bold 1.4em Verdana;
}
#msgCloseButton{
float:right;
}
And finally here is the javascript to setup the close button and functions to show and hide the message bar:
/* Document Ready */
$(function () {
SetupNotifications();
});
SetupNotifications = function () {
//setup close button in msgBox
$("#msgCloseButton").click(function (e) {
e.preventDefault();
CloseMsg();
});
}
DisplayMsg = function (sMsg) {
//set the message text
$("#msgText").text(sMsg);
//show the message
$('#msgBox').slideDown();
}
CloseMsg = function () {
//hide the message
$('#msgBox').slideUp();
//clear msg text
$("#msgtText").val("");
}
To perform a simple test you could try this:
Show Message!
Something like this?
$("#bar").slideUp();
However, here I think they fade out first the bar then they bring the main container up, so that'd be something like that:
$("#bar").fadeOut(function(){
$("#container").animate({"top":"0px"});
});

Categories