I've tried all the solutions from other Stackoverflow topics, but I can't my jQuery file to work.
I use a Wampserver to test my code and I test inside of multiple browsers (Firefox, Chrome, Opera). Same problem every time.
HTML
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
I've put these lines before my closing <\body> tag
scripts.js`
(function($) {
'use strict';
// holds current image shown
var $currNr = 0;
var links, images;
/**
* Function to prevent closures; adds click event handler to links
*/
var addEvents = function(nr) {
// add click event to link
$(links[nr]).on('click', function(e) {
showImage(nr);
e.preventDefault();
});
};
/**
* Function to show an image
*/
var showImage = function(nr) {
// find image
var $img = $(images[nr]);
if (!$img) return;
// find big image
var $photoBig = $('#photoBig');
// change
$photoBig.attr('src', $img.attr('data-src-l'));
$photoBig.attr('alt', $img.attr('alt'));
// remember current image number
$currNr = nr;
};
/**
* Function to show the next image
*/
var showNextImage = function() {
if ($currNr != (links.length - 1)) {
showImage($currNr + 1);
} else {
showImage(0);
}
};
/**
* Function to show the previous image
*/
var showPrevImage = function() {
if ($currNr != 0) {
showImage($currNr - 1);
} else {
showImage(links.length - 1);
}
};
// start scripts
$(window).on('load', function() {
// find images and links
links = $('#thumbsmenu li>a');
images = $('#thumbsmenu li>a img');
// add link events
$(links).each(function(nr) {
$(this).on('click', function(e) {
showImage(nr);
e.preventBubble();
});
});
// controls
$('#lnkFirst').on('click', function(e) {
showImage(0);
e.preventDefault();
});
$('#lnkPrev').on('click', function(e) {
showPrevImage();
e.preventDefault();
});
$('#lnkNext').on('click', function(e) {
showNextImage();
e.preventDefault();
});
$('#lnkLast').on('click', function(e) {
showImage(images.length - 1);
e.preventDefault();
});
// keyboard
$(document).on('keydown', function(e) {
var $code = (e.keyCode ? e.keyCode : e.which);
switch (event.keyCode) {
case 37: showPrevImage(); e.preventDefault(); break;
case 39: showNextImage(); e.preventDefault(); break;
}
});
// play
var $timer;
$('#btnPlay').on('click', function(e) {
if (!$(this).prop('playing')) {
$(this).val('stop');
$(this).prop('playing', true);
$currNr = 0;
$timer = setInterval(showNextImage, 1000);
} else {
$(this).val('start');
$(this).prop('playing', false);
clearInterval($timer);
}
});
});})(jQuery);`
I use a self-invoking function and use it as parameter but I get a:
ReferenceError: jQuery is not defined
Normally this code should work, that was how I was taught back then. Anyone an idea what could be the real issue here?
You are loading scripts.js before jQuery
Change the following code:
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
To:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>
Your script load ordering is wrong. Load jQuery first, then use it.
As other people suggested your order is wrong. In order for you to use JQuery in other script files it needs to be fully loaded. Change your HTML like so:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>
Related
I have to admin a quite small web presentation with only some javascript. It was written some years ago and now I try to implement a mobile compatible menu.
This are the versions of jQuery which were installed before I started with the new menu:
jQuery.min.js : jQuery JavaScript Library v1.6.1
jQuery.tools.overlay.min.js : jQuery Tools v1.2.7 - The missing UI library for the Web
jQuery-ui.min.js : jQuery UI 1.8.13
Now I try several newer jQuery code, and at the moment I use this versions:
<script src="scripts/jquery-1-12-3.min.js" type="text/javascript"></script>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
The plug in I want to use for the menu is "doubletaptogo.js":
(function($) {
/*
Responsive Flat Menu
http://cssmenumaker.com/menu/responsive-flat-menu
*/
$.fn.menumaker = function(options) {
var cssmenu = $(this),
settings = $.extend({
title: "Menu",
format: "dropdown",
sticky: false
}, options);
return this.each(function() {
cssmenu.prepend('<div id="menu-button">' + settings.title + '</div>');
$(this).find("#menu-button").on('click', function() {
$(this).toggleClass('menu-opened');
var mainmenu = $(this).next('ul');
if (mainmenu.hasClass('open')) {
mainmenu.hide().removeClass('open');
} else {
mainmenu.show().addClass('open');
if (settings.format === "dropdown") {
mainmenu.find('ul').show();
}
}
});
cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
cssmenu.find(".has-sub").prepend('<span class="submenu-button"></span>');
cssmenu.find('.submenu-button').on('click', function() {
$(this).toggleClass('submenu-opened');
if ($(this).siblings('ul').hasClass('open')) {
$(this).siblings('ul').removeClass('open').hide();
} else {
$(this).siblings('ul').addClass('open').show();
}
});
};
if (settings.format === 'multitoggle') multiTg();
else cssmenu.addClass('dropdown');
if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
if ($(window).width() > 768) {
cssmenu.find('ul').show();
}
if ($(window).width() <= 768) {
cssmenu.find('ul').hide().removeClass('open');
}
};
resizeFix();
return $(window).on('resize', resizeFix);
});
};
})(jQuery);
/*
By Osvaldas Valutis, www.osvaldas.info
Available for use under the MIT License
*/
;
(function($, window, document, undefined) {
$.fn.doubleTapToGo = function(params) {
if (!('ontouchstart' in window) &&
!navigator.msMaxTouchPoints &&
!navigator.userAgent.toLowerCase().match(/windows phone os 7/i)) return false;
this.each(function() {
var curItem = false;
$(this).on('click', function(e) {
var item = $(this);
if (item[0] != curItem[0]) {
e.preventDefault();
curItem = item;
}
});
$(document).on('click touchstart MSPointerDown', function(e) {
var resetItem = true,
parents = $(e.target).parents();
for (var i = 0; i < parents.length; i++)
if (parents[i] == curItem[0])
resetItem = false;
if (resetItem)
curItem = false;
});
});
return this;
};
})(jQuery, window, document);
/**
* doubleTapToGoDecorator
* Adds the ability to remove the need for a second tap
* when in the mobile view
*
* #param {function} f - doubleTapToGo
*/
function doubleTapToGoDecorator(f) {
return function() {
this.each(function() {
$(this).on('click', function(e) {
// If mobile menu view
if ($('#menu-button').css('display') == 'block') {
// If this is not a submenu button
if (!$(e.target).hasClass('submenu-button')) {
// Remove the need for a second tap
window.location.href = $(e.target).attr('href');
}
}
});
});
return f.apply(this);
}
}
// Add decorator to the doubleTapToGo plugin
jQuery.fn.doubleTapToGo = doubleTapToGoDecorator(jQuery.fn.doubleTapToGo);
/**
* jQuery
*/
(function($) {
$(document).ready(function() {
$("#cssmenu").menumaker({
title: "Menu",
format: "multitoggle"
});
$('#cssmenu li:has(ul)').doubleTapToGo();
});
})(jQuery);
The menu looks like:
<nav id='cssmenu' role='navigation'>
Show navigation
Hide navigation
<ul>...
...and when I debug with Firebug I always see the error mentioned in subject of this post!
Are there still problems with the versions of jQuery? I'm very sorry, but I'm not used to programming very much in javascript.
Thanks a lot for your help in advance!
I added now
<script type="text/javascript" src="scripts/jquery-ui.min.js" ></script> // v1.11.4
I bind the doubletaptogo with that code to the body of my html:
<script type="text/javascript">
$(function () {
$('.cssmenu').doubleTapToGo();
});
</script>
So far, it unfortunately does not work.
With this doubletaptogo.min.js I have a fine menu on my Laptop, without an error in Firebug, but no menu on my mobile Units:
;(function(e,t,n,r){e.fn.doubleTapToGo=function(r){if(!("ontouchstart"in t)&&!navigator.msMaxTouchPoints&&!navigator.userAgent.toLowerCase().match(/windows phone os 7/i))return false;this.each(function(){var t=false;e(this).on("click",function(n){var r=e(this);if(r[0]!=t[0]){n.preventDefault();t=r}});e(n).on("click touchstart MSPointerDown",function(n){var r=true,i=e(n.target).parents();for(var s=0;s<i.length;s++)if(i[s]==t[0])r=false;if(r)t=false})});return this}})(jQuery,window,document);
With that doubletaptogo.js there is an error in Firebug (like mentioned in the subject), but a fine menu on my Laptop, and a "Menu" on my mobile Units which does not react on anything. I tried also to Change the find() against a filter(), but then the filter() was "not a function".
What else can be the Problem?
I also tried to use only the code of that site as a menu, just to Show it on my site:
http://codepen.io/dmitrykiselyov/pen/XJwqZM
...and this did not work also. There was only the "Menu" on my mobile Units which did not react.
So, may be Problem with the jQuery? I use now the jquery-1-12-3.min.js and the ui is Version v1.11.4.
May be a bad combination?
I got same error, solution is please use the latest jQuery version from 1.x.y serie (you can pick here: https://code.jquery.com/jquery/ 1.12.4 is working well for me).
Every time when I try to run this code in visual studio I get the above error. I am not sure what is going on. I know it's question like this, but I did not see this error in the answered in the solutions to this problem. Can anyone help me with this?
// display the lightbox
function lightbox() {
var insertContent = "<div id='chartCon'>Test</div>";
// jQuery wrapper (optional, for compatibility only)
(function ($) {
// add lightbox/shadow <div/>'s if not previously added
if ($('#lightbox').size() == 0) {
var theLightbox = $('<div id="lightbox" class="highcharts-container"/>');
var theShadow = $('<div id="lightbox-shadow"/>');
$(theShadow).click(function (e) {
closeLightbox();
});
$('body').append(theShadow);
$('body').append(theLightbox);
//$().keydown(function (e) {
// if (e.which == 27) {
// closeLightbox();
// }
//});
}
// remove any previously added content
$('#lightbox').empty();
// insert HTML content
if (insertContent != null) {
$('#lightbox').append(insertContent);
}
//create chart
var chart = $('#ChartContainer').highcharts('StockChart');
var annots = chart.exportData()
window.chartwidth = $('#ChartContainer').width();
//chart.destroy();
window.chartops.series = window.seriesOptions;
$('#lightbox').highcharts('StockChart', window.chartops);
$('#lightbox').highcharts('StockChart').importData(annots);
// move the lightbox to the current window top
$('#lightbox').css('top', $(window).scrollTop());
// display the lightbox
$('#lightbox').show();
$('#lightbox-shadow').show();
})(jQuery); // end jQuery wrapper
}
// close the lightbox
function closeLightbox() {
// jQuery wrapper (optional, for compatibility only)
(function ($) {
//export possibly changed annotations and reset chartwidth
var chart = $('#lightbox').highcharts('StockChart');
var annots = chart.exportData()
$('#ChartContainer').highcharts('StockChart').removeAllAnnotations();
$('#ChartContainer').highcharts('StockChart').importData(annots);
window.chartwidth = $('#ChartContainer').width();
// hide lightbox/shadow <div/>'s
$('#lightbox').hide();
$('#lightbox-shadow').hide();
// remove contents of lightbox in case a video or other content is actively playing
$('#lightbox').empty();
})(jQuery); // end jQuery wrapper
}
Sorry, this is the function giving me the error
init: function (chart) {
var rangeSelector = this,
options = chart.options.rangeSelector,
buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons),
selectedOption = options.selected,
blurInputs = rangeSelector.blurInputs = function () {
var minInput = rangeSelector.minInput,
maxInput = rangeSelector.maxInput;
if (minInput) {
minInput.blur();
}
if (maxInput) {
maxInput.blur();
}
};
I am still new to script, this my be a simple question.
On the site I am building right now I have some small script functions that work great, but when I linked in jQuery for a different function the first ones stopped working. If I remove the jQuery link they work again.
Here is the functions that I have currently:
This one is the one I need jQuery for, <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
// ~~~~~~~~~~ Header Background image rotation ~~~~~~~~~~ \\
$(document).ready(function(){
var header = $('.mainheader');
var backgrounds = new Array(
'url(img/rainbow.jpg)'
, 'url(img/chicks_on_grass.jpg)'
, 'url(img/cattle_on_pasture.jpg)'
, 'url(img/csa_bundle.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 10000);
header.css('background-image', backgrounds[0]);
});
This next function still works normally
// ~~~~~~~~~~ ShowOrHide Element Onclick ~~~~~~~~~~ \\
function showOrHide(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
This one does not work any more
// ~~~~~~~~~~ Form Email Hint ~~~~~~~~~~ \\
JotForm.init(function(){
$('input_4').hint('ex: myname#example.com');
});
All three of these functions are enclosed in <script language="JavaScript"></script> tag.
Then I have a third party JavaScript link that controls some things on a form that I have on the site. <script src="http://max.jotfor.ms/min/g=jotform?3.1.1667" type="text/javascript"></script> This does not work alongside the JQuery either.
I have no idea what is going on, spent all day working on it. Any help is appreciated.
This is a conflict issue, refer to this page for further documentation
do this:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var $j = jQuery.noConflict();
// ~~~~~~~~~~ Header Background image rotation ~~~~~~~~~~ \\
$j(document).ready(function(){
var header = $j('.mainheader');
var backgrounds = new Array(
'url(img/rainbow.jpg)'
, 'url(img/chicks_on_grass.jpg)'
, 'url(img/cattle_on_pasture.jpg)'
, 'url(img/csa_bundle.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 10000);
header.css('background-image', backgrounds[0]);
});
// ~~~~~~~~~~ ShowOrHide Element Onclick ~~~~~~~~~~ \\
function showOrHide(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
</script>
I attempted to combine two functions in the code below. All seems to be working except I cannot get the variable currentImage.metaData.something to work in the second function. I appreciate your advice.
<script type="text/javascript" src="code.photoswipe-2.1.5.min.js"></script>
<script type="text/javascript">
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function(){
var
options = {
getImageMetaData: function(el){
return {
href: el.getAttribute('href'),
something: el.getAttribute('data-something'),
anotherThing: el.getAttribute('data-another-thing')
}
}
},
instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage, function(e){
var currentImage = instance.getCurrentImage();
console.log(currentImage.metaData.something);
console.log(currentImage.metaData.anotherThing);
});
}, false);
}(window, window.Code.Util, window.Code.PhotoSwipe));
(function(window, Util, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function(){
var
sayHiEl,
sayHiClickHandler = function(e){
alert('yo!!!');
}
options = {
getToolbar: function(){
return '<div class="ps-toolbar-close" style="padding-top: 12px;">Close</div><div class="ps-toolbar-play" style="padding-top: 12px;">Play</div><div class="ps-toolbar-previous" style="padding-top: 12px;">Previous</div><div class="ps-toolbar-next" style="padding-top: 12px;">Next</div><div class="say-hi" style="padding-top: 12px;">Say Hi!</div>';
// NB. Calling PhotoSwipe.Toolbar.getToolbar() wil return the default toolbar HTML
}
},
instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
// onShow - store a reference to our "say hi" button
instance.addEventHandler(PhotoSwipe.EventTypes.onShow, function(e){
sayHiEl = window.document.querySelectorAll('.say-hi')[0];
});
// onToolbarTap - listen out for when the toolbar is tapped
instance.addEventHandler(PhotoSwipe.EventTypes.onToolbarTap, function(e){
if (e.toolbarAction === PhotoSwipe.Toolbar.ToolbarAction.none){
if (e.tapTarget === sayHiEl || Util.DOM.isChildOf(e.tapTarget, sayHiEl)){
alert(currentImage.metaData.anotherThing);
}
}
});
// onBeforeHide - clean up
instance.addEventHandler(PhotoSwipe.EventTypes.onBeforeHide, function(e){
sayHiEl = null;
});
}, false);
}(window, window.Code.Util, window.Code.PhotoSwipe));
You're declaring the currentImage variable within the first function. Variables created with the var keyword are function-scoped, meaning that it isn't visible outside of the function (and hence not visible in your second function, in this case).
I would probably suggest some more general code reorganization, but an easy fix would be to declare the variable above both of your functions, making it visible to both.
Need to apply a var to a statement if its conditions are met, this syntax isn't throwing errors but its not working.
<script type="text/javascript">
$(document).ready(function(){
var action_is_post = false;
//stuff here
$(this).ready(function () {
if ($("#stepDesc0").is(".current")) {
action_is_post = true;
}
});
//stuff here
</script>
should I use something other than .ready? Do I even need the $(this).ready(function ()... part? I need it to apply the var when #stepDesc0 has the class current.
$(document).ready(function(){
var action_is_post = false;
$("form").submit(function () {
action_is_post = true;
});
if ($("#stepDesc0").is(".current")) {
var action_is_post = true;
}
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
}
});
<script type="text/javascript">
$(document).ready(function(){
var action_is_post=$("#stepDesc0").is(".current");
});
</script>
If you want the variable to be accessible outside the $(document).ready(function(){..., then you'll need to declare it outside the statement like this:
<script type="text/javascript">
var action_is_post;
$(document).ready(function(){
action_is_post=$("#stepDesc0").is(".current");
});
</script>
HTML (in order to test it):
Show value
$(function() {
var actionIsPost = $('#stepDesc0').is('.current');
alert( actionIsPost );
});
If you are adding the current class to #stepDesc0 on an event then put the .is check in the event handler.