Jquery isn't recognized in simple html5 web page - javascript

I have been searching whole afternoon for a solution, but I didn't found it. I am writing a HTML5 webpage, using jquery and css. I'm trying to implement very simple drop down menu (I found tutorial here) but it does not work for me. I have copy paste this code from this article to a local html file and open it in browser and it works great, just as I want to implement menu, but when I try to implement the same code in my webpage it doesn't work.
I get in my console log displayed two errors:
(SyntaxError: function statement requires a name - jquery.js: row 2072) and then after this error i get
(ReferenceError: $ is not defined - index.html row 15, where the $ sign occurs).
I have been searching a lot, but I didn't found anything usefull which might help me. I have also checked number of times if I might have problem in jquery script declaration but It's ok. I don't have any idea why this simple code don't work in my application but in external code it works just fine. I have also try to insert language and text type on script tag, but I didn't work, neither if I leave script tag empty. I use latest Mozilla Firefox browser.
Here is my application code:
<!DOCTYPE html>
<html>
<head>
<title>Test title</title>
<link rel="stylesheet" type="text/css" href="css/layout.css">
<link rel="stylesheet" type="text/css" href="css/skin/default.css">
<script src="script/jquery.js" type="text/javascript"></script>
<script src="script/video.js" type="text/javascript"></script>
<script src="script/picture.js" type="text/javascript"></script>
<script src="script/ApplicationController.js" type="text/javascript"></script>
<script>
$("body").ready(function() {
$(".dropdown").hover(function() {
$(this).find(".sub_navigation").slideToggle();
});
});
</script>
</head>
<body onload="onApplicationLoad()">
<div id="header">
<img id="logo" src="images/logo.png" alt="Logo" width="200" height="38" />
<div id="verticalHeaderLine"></div>
<div id="headerMenu">
<ul id="navigation">
<li class="dropdown"> <button id="Login" class="button" title="Edit Login">Login</button>
<ul class="sub_navigation">
<li><button id="test" class="button" title="Edit Test">Test</button></li>
<li><button id="test1" class="button" title="Edit Test">Test 1</button></li>
<li><button id="test2" class="button" title="Edit Test">Test 2</button></li>
</ul>
</li>
</ul>
</div>
</div>
</body>
</html>
and this is a css related to menu:
ul {
margin:0;
padding:0;
list-style-type:none;
min-width:200px;
}
ul#navigation {
float:left;
}
ul#navigation li {
float:left;
min-width:200px;
}
ul.sub_navigation {
position:absolute;
display:none;
}
ul.sub_navigation li {
clear:both;
}
I would be very happy if someone know what do I do wrong and if he could be so kind and tolk me what do I do wrong.
Regards,
Dahakka

$("body").ready(function() { should be $(document).ready(function() {
It's usually better to let Google host jQuery for you. See http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/ for a full explanation. Replace your reference to jQuery with
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Also, at the end of your document, you have <body><html> instead of </body></html>

I think jquery is not being found. try adding this to your <head></head>.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
This is the google hosted jquery. If you have internet access it should at least solve your first problem

jQuery(document).ready(function($) {
$(".dropdown").hover(function() {
$(this).find(".sub_navigation").slideToggle();
});
});
Try this to see if there is a conflict or just jQuery isn't loaded at all.

Related

JavaScript doesn't work with bootstrap 4 + thymeleaf

I'm developing a web app with Spring Boot, Bootstrap 4 and Thymeleaf.
I want to show a bootstrap alert, and then, it hides automatically after seconds (just like a "sucessfully" notification).
I have found a lot of solutions, but all of then need JavaScript. When I tried to use JS on my project, it doesn't work.
I use a default template, which is used in the others views through layout:decorate="~{default}". In this default template, I have the Bootstrap link and scripts:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
...
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
If a put in any view the following code, it does nothing.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
...
</head>
<body class="text-center">
<div layout:fragment="content">
<div class="product-options">
<a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong> Product have added to your wishlist.
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").fadeTo(2000, 500)
.slideUp(500, function () {
$("#successalert").slideUp(500);
});
});
});
</script>
...
</div>
</body>
NOTE: This is just an example to check that JS doesn't work. I takes it from this post.
When I run this code, the alert is showed, but it never disappears. I have tried with a lot of scripts and never work.
Could be a compatibility version problem?
Hi I think this post address your problem:
Why does jQuery throw the error `fadeOut is not a function'?
In this line <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> you use the slim version of Jquery not the full-one, this prompt when I click to "Add to Wishlist" link" a TypeError in the Firefox develloper tool console.
TypeError: $(...).fadeTo is not a function, this means that the Jquery javascript object $("#success-alert") doesn't have attached a fadeTo function.
You can get the full minified version here: https://code.jquery.com/
Snippet from https://code.jquery.com
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
PS: If you don't need SRI you can remove integrity and crossorigin attributes.

Jquery function .appendTo() not working

I am making a text-based game to test my knowledge of HTML, CSS, JavaScript and jQuery. I am trying to use the jQuery .appendTo() function to append a <p> element to div.defaultDisplay when the "Play Now!" button is clicked, but no matter what I do, it doesn't seem to work. I have tried using <span> instead of <p>, I've tried .append(), I've tried appending it to the input button using $("input[type='button']") and $("#playNow") with both .append() and .appendTo(), so I really don't know. It could be an error in the JS file or there could be something wrong with the HTML code. Everything else is displaying just fine, but the button isn't doing anything when clicked. Here is my code:
HTML (game.html):
<head>
<title>A Pretty Awesome Game</title>
<link href="game.css" rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="game.js"></script>
</head>
<body>
<div class="defaultDisplay">
<h1>A Pretty Awesome Game</h1>
<input type="button" value="Play Now!" id="playNow">
</div>
</body>
</html>
CSS (game.css):
#import url(https://fonts.googleapis.com/css?family=Spectral);
body {
font-family: Spectral;
background-image: -webkit-linear-gradient(#FFF, #000);
background-size: cover;
background-repeat: no-repeat;
}
input, button {
font-family: Spectral;
}
JS (game.js):
function showPartOne() {
$("#playNow").click(function() {
$("<p>test</p>").appendTo(".defaultDisplay");
});
}
showPartOne();
Please help!
Edit: Thanks KevBot, it seems to be working when I run your code snippet but it still doesn't work on my webpage! I've updated my code in this answer as well.
Answer after question edit:
Your game.js has JS searching for HTML that does not yet exist (it reads and runs the JS before reading the HTML). You can quickly solve this by moving your script tag to just before the closing body tag:
You should end up with the following:
<!DOCTYPE html>
<html>
<head>
<title>A Pretty Awesome Game</title>
<link href="game.css" rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="defaultDisplay">
<h1>A Pretty Awesome Game</h1>
<input type="button" value="Play Now!" id="playNow">
</div>
<script src="game.js"></script>
</body>
</html>
Original Answer:
You wrapped your code in a function that was never executed. Either put the jQuery event listener code outside of the function, or just call the function:
function showPartOne() {
$("#playNow").click(function() {
$("<p>test</p>").appendTo(".defaultDisplay");
});
}
showPartOne();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="defaultDisplay">
<h1>A Pretty Awesome Game</h1>
<input type="button" value="Play Now!" id="playNow">
</div>
Your syntax is absolutely file, It might be not triggering because showPartOne() is not getting called and hence click event is not getting bind.
Kindly call showPartOne() somewhere in the application.
Can you check this
function showPartOne() {
$("#playNow").click(function() {
$(".defaultDisplay").append("<p>test</p>");
});
}

Load content of external header on other page

I've only started working on my website and I've already run into a little hiccup, for some reason a script that I use doesn't work anymore and I can't find any fixes, there's nothing in the chrome console or any useful error information.
I was hoping you guys could help me out.
I'm simply trying to load a piece of a different HTML page onto my Index page.
Usually I run this script, and it should take the #nav div from the header.html and put it into the header below the script.
Index.html:
<!--added scripts-->
<script src="jquery/jquery-3.2.0.min.js"></script>
<!-- Css -->
<link rel="stylesheet" type="text/css" href="Sjvklusbedrijf.css">
<!--script-->
<script>
$(document).ready(function() {
$("#header").load("header.html #nav");
alert("test");
});
</script>
</head>
<body>
<header id="header">
</header>
requested script:
<div id="#nav">
<div class="logodiv"></div>
<ul>
<li>Home</li>
<li>Foto's</li>
<li>Garantie</li>
<li>Contact</li>
</ul>
I'm using jquery and have loaded it thusly: <script src="jquery/jquery-3.2.0.min.js"></script> and if I put an alert in the doc.ready script it pops up but it doesn't load the required data
I'm running on localhost but that shouldn't be a problem for jquery
Thanks for the help!
It did not work the first time because <div id="#nav"> should be <div id="nav">.
okay somehow it decided to work but I don't really get why.
I changed some things:
index:
<script>
$(document).ready(function() {
$("#header").load("header.html nav");
});
</script>
</head>
<body>
<!--header-->
<header id="header" class="header">
</header>
required script:
<nav>
<img src="fotos/test" alt="logo"/>
<ul>
<li>Home</li>
<li>Foto's</li>
<li>Garantie</li>
<li>Contact</li>
</ul>

Browser doesn't recognize inclusion of external javascript/jquery file

In my Dynamic Web Project (Eclipse), developed with the Spring MVC framework, I have the JSP page below, placed in the folder WEB-INF/jsp/ :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HorarioLivre</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="js/index.js"></script>
<link rel="stylesheet" href="css/style-main.css">
<link rel="stylesheet" href="css/style-popup.css">
</head>
<body>
<header>
<div class="container">
<h1>HorarioLivre</h1>
<nav>
<ul>
<li>Eventos</li>
<li>Cadastrar Horarios</li>
<li>Listar Horarios</li>
<li>Usuarios</li>
<li>${usuario.nome}
<ul>
<li>Perfil</li>
<li>Configurações</li>
<li>Logout</li>
</ul>
</li>
</ul>
</nav>
</div>
</header>
<div id="results">
Fechar
<div id="content"></div>
</div>
</body>
</html>
My problem is that apparently the application don't be reading the js/index.js file, placed in folder WebContent/js (the css files, placed in WebContent/css, are read normally). When I put some javascript / jquery code directly in the JSP page (like the code displayed in the question Browser doesn't recognize javascript / jquery code), they are executed without any problems.
Someone can find the problem with this page?
Update 1
$(document).ready(function(){
setupPopup();
});
function setupPopup() {
$('a').click(function() {
$('#content').load($(this).attr('href'));
$('#container').append('<div id="cover">');
$('#results').fadeIn(500);
popupPosition();
});
$('#close').click(function() {
$('#results').fadeOut(100);
$('#cover').remove();
});
$(window).bind('resize', popupPosition);
}
function popupPosition() {
if(!$("#results").is(':visible')){ return; }
$("#results").css({
left: ($(window).width() - $('#results').width()) / 2,
top: ($(window).width() - $('#results').width()) / 7,
position:'absolute'
});
$('#results').draggable();
}
FINAL UPDATE
In the end, I choose don't use jquery, and replace the code from the header by this:
<script>
function handleClick(url){
document.getElementById("results").style.display = 'block';
document.getElementById("content").innerHTML='<object type="text/html" data="'+url+'" ></object>';
}
function cleanDiv() {
document.getElementById("results").style.display = 'none';
document.getElementById("content").innerHTML=' ';
}
</script>
each link has this format:
Eventos
and the html code for my popup window get this form:
<section class="about" id="results" style="left: 183px; top: 111px;" onMouseDown="dragStart(event, 'results');">
<div align="right">X</div>
<div id="content" align="center"></div>
</section>
With the parte style="left: 183px; top: 111px;" onMouseDown="dragStart(event, 'results');" being responsible for move the popup across the screen (See the question how to drag and drop a <div> across the page)
I'm not entirely sure, but I think i've seen this done before:
remove http: and https: from your js sources. So it should look like this:
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
This might not work, it was just a thought I had.
It's not the best solution, but you can try load script dynamically with jQuery.load or something like
<script>document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script>
Try <script src="/js/index.js"></script> instead.
edit: This Absolute path & Relative Path explains the relative and absolute path in more detail.
I would suggest viewing the source code once your run your JSP in browser (right click - view page source or something similar, depending on your browser). You should see what URL for the JS the page is trying to load and should be able to correct it accordingly.
Also, perhaps it's just your context path missing from the URL. In that case, I'd use <c:url> tags when generating the URL.

Implementing JQuery Scrollbox - amending the function - not sure how to do it

I'm working with a blog and I wanted to place a JQuery scroll bar into my div box for the main content area. I'm kind of new to JS but I think I missed something. The devs provided a script but I don't believe its correct. Just a side note: all the libraries are loaded before the script so I don't believe that's where the problem is. Here is what I current have (MINUS all the Sql crap):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="../css/Styles.css" rel="stylesheet" type="text/css" />
<link href="../css/jquery.mCustomScrollbar.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="BKlayer2">
<img src="../Images/BKlayer2.png" />
<div class="InnerContent1">
<img src="../Images/innerContent1.png" />
</div>
<div class="innerContent2">
<img src="../Images/innerContent2.png" />
</div>
<div class="Feedback">
<img src="../Images/Feedblockbk.png" />
</div>
<div id="blog_Posts">
<?php do { ?> Updated on: <?php echo $row_displayBehaviors['formatted']; ?><br />
<br />
<?php echo $row_displayBehaviors['title']; ?>
<br />
<br />
<?php echo $row_displayBehaviors['blog_entry']; ?>
<p> </p>
<?php } while ($row_displayBehaviors = mysql_fetch_assoc($displayBehaviors)); ?>
</div>
<?php
mysql_free_result($getArchives);
mysql_free_result($displayBehaviors);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="jquery.mCustomScrollbar.concat.min.js"></script>
<script>
(function($){
$(window).load(function(){
$(".blog_Posts").mCustomScrollbar();
theme:"light"
});
})(jQuery);
</script>
</body>
</html>
I changed .content to .blog_Posts because that's the div box I'm trying to apply this too. I checked all other css and additional info to make sure .content was not referenced anywhere else.
After uploading scripts and all other relevant information to my server, I checked in firebug to find out the problem.
Now firebug is giving me this error:
TypeError: $(...).mCustomScrollbar is not a function
[Break On This Error]
$(".blog_Posts").mCustomScrollbar();
I think firebug said it better than I could. I didn't see a function defined here. I'm not exactly sure what the function would be if it has to be included.
It sounds to me like you haven't included the jQuery plugin script.
mCustomScrollbar is not a part of jQuery, you'll need to reference the plugin.
This sounds like the plugin you are talking about, include the script reference from there:
http://manos.malihu.gr/jquery-custom-content-scroller/
I figured it out. Just if anyone wants to know:
I did it by working backwards on the demo script and figuring it out. Basically what I didn't do was have the CSS lined up and I also didn't have the scripts in the correct directories.
As for the proper script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/minified/jquery-1.9.1.min.js"%3E%3C/script%3E'))</script>
<!-- custom scrollbars plugin -->
<script src="jquery.mCustomScrollbar.concat.min.js"></script>
<script>
(function($){
$(window).load(function(){
$(".body,.content").mCustomScrollbar({
scrollButtons:{
enable:true
}
});
});
})(jQuery);
</script>
basically I added in the .body in and changed .content so it corresponded to my main styles sheet. You really don't need any css on your page other than this:
<style>
body>.mCustomScrollBox>.mCSB_scrollTools{top:2%; height:96%;}
</style>
That's the key I was missing.

Categories

Resources