JS works on CodePen but not locally [duplicate] - javascript

This question already has answers here:
Why is simple JavaScript code not running?
(3 answers)
Closed 1 year ago.
I'm trying to get a JS slider to work. I'm using Brackets as my code environment.
I have tried creating a local .js file and putting
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
<script type="text/javascript" src="my.js"></script>
line in <head>
I have also tried just putting only <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> in <head> and then putting all of the script code within a <script> tag in <head>.
CodePen for that:
https://codepen.io/hiarooo/pen/zYNboJq
As you can see, the slider doesn't function properly.
However, I have noticed that if I simply put the code in the JS box of CodePen (I have commented it, but you can try uncommenting it to see what I mean) then the Slider functions perfectly.
What is wrong with the way I am doing things? I do not understand.
Thank you for any advice.

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypter | Upload01</title>`enter code here`
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght#700&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!--<script type="text/javascript" src="my.js"></script>-->
</head>
<body>
<section class="section-slider">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Neucha' rel='stylesheet' type='text/css'>
<div id="wrapper">
<div id="slider-wrap">
<ul id="slider">
<li data-color="#1abc9c">
<div>
<h3>What is cat</h3>
<span>it is a cat</span>
</div>
<i></i>
</li>
<li data-color="#3498db">
<div>
<h3>Slide #2</h3>
<span>Sub-title #2</span>
</div>
<i class="fa fa-gears"></i>
</li>
<li data-color="#9b59b6">
<div>
<h3>Slide #3</h3>
<span>Sub-title #3</span>
</div>
<i class="fa fa-sliders"></i>
</li>
<li data-color="#34495e">
<div>
<h3>Slide #4</h3>
<span>Sub-title #4</span>
</div>
<i class="fa fa-code"></i>
</li>
<li data-color="#e74c3c">
<div>
<h3>Slide #5</h3>
<span>Sub-title #5</span>
</div>
<i class="fa fa-microphone-slash"></i>
</li>
</ul>
<!--controls-->
<div class="btns" id="next"><i class="fa fa-arrow-right"></i></div>
<div class="btns" id="previous"><i class="fa fa-arrow-left"></i></div>
<div id="counter"></div>
<div id="pagination-wrap">
<ul>
</ul>
</div>
<!--controls-->
</div>
</div>
</section>
<script>
//current position
var pos = 0;
//number of slides
var totalSlides = $('#slider-wrap ul li').length;
//get the slide width
var sliderWidth = $('#slider-wrap').width();
$(document).ready(function(){
/*****************
BUILD THE SLIDER
*****************/
//set width to be 'x' times the number of slides
$('#slider-wrap ul#slider').width(sliderWidth*totalSlides);
//next slide
$('#next').click(function(){
slideRight();
});
//previous slide
$('#previous').click(function(){
slideLeft();
});
/*************************
//*> OPTIONAL SETTINGS
************************/
//automatic slider
var autoSlider = setInterval(slideRight, 3000);
//for each slide
$.each($('#slider-wrap ul li'), function() {
//set its color
var c = $(this).attr("data-color");
$(this).css("background",c);
//create a pagination
var li = document.createElement('li');
$('#pagination-wrap ul').append(li);
});
//counter
countSlides();
//pagination
pagination();
//hide/show controls/btns when hover
//pause automatic slide when hover
$('#slider-wrap').hover(
function(){ $(this).addClass('active'); clearInterval(autoSlider); },
function(){ $(this).removeClass('active'); autoSlider = setInterval(slideRight, 3000); }
);
});//DOCUMENT READY
/***********
SLIDE LEFT
************/
function slideLeft(){
pos--;
if(pos==-1){ pos = totalSlides-1; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************
SLIDE RIGHT
*************/
function slideRight(){
pos++;
if(pos==totalSlides){ pos = 0; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************************
//*> OPTIONAL SETTINGS
************************/
function countSlides(){
$('#counter').html(pos+1 + ' / ' + totalSlides);
}
function pagination(){
$('#pagination-wrap ul li').removeClass('active');
$('#pagination-wrap ul li:eq('+pos+')').addClass('active');
}
</script>
</body>
Try putting this way it works fine,because If you have code in your JavaScript that alters HTML as soon as the JavaScript file loads, there won't actually be any HTML elements available for it to affect DOM yet, so it will seem as though the JavaScript code isn't working, and you may get errors.Thanks :)

Related

jQuery load executes but callback is not executed

I am kinda new to website development, so I am asking for some help on the matter. I have the following snippet of html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--CSS Styles -->
<link rel="stylesheet" href="../assets/css/styles.css"/>
</head>
<body>
<!--Navigation bar-->
<div id="nav-placeholder"></div>
<!--end of Navigation bar-->
</body>
<script src="../assets/js/navigation_bar.js" type="text/javascript", locator="about"></script>
</html>
It calls the navigation_bar.js script provided here
locator = document.currentScript.getAttribute('locator');
function changeActiveElement(element_id){
console.log("Called");
nav_element = document.getElementById("navigation");
for (i = 0; i < nav_element.length; i++) {
console.log(nav_element[i].id)
if(nav_element[i].id == element_id) document.getElementById(element_id).className = "active-nav-link";
else document.getElementById(element_id).className = "nav-link";
}
}
$(function()
{$("#nav-placeholder").load("/assets/html/nav.html", function(){
changeActiveElement(locator);
});}
);
whereas the nav.html file is here:
<nav>
<h1>Some name</h1>
<ul id="navigation" class="navigation">
<li><a id="about" href="/pages/about.html" class="nav-link">About</a></li>
<li><a id="compt" href="#compt" class="nav-link">Competences</a></li>
<li><a id="projects" href="#projects" class="nav-link">Projects</a></li>
<li><a id="contact" href="#contact" class="nav-link">Contact</a></li>
</ul>
<button class="burger-menu" id="burger-menu">
<ion-icon class="bars" name="menu-outline"></ion-icon>
</button>
</nav>
The scope of the snippet is to change the class of the a tags listed in the navigation element. The navigation bar is correctly loaded via $("#nav-placeholder").load("/assets/html/nav.html"), yet changeActiveElement function is never executed via the callback.
Can someone explain me this behaviour?
I tested your code and everything is working except that nav_element is not a list and therefore nav_element.length throws an error. You could use document.querySelectorAll("#navigation"); instead, which returns a node list of all selected elements. Although, I would not recommend doing a for loop on elements by id. Use classes to select the elements. Id is only for one element.

Materializecss sidenav not working

I am trying to get the sidenav to work for the Materializecss framework.
MATERIALIZECSS http://next.materializecss.com/getting-started.html
SIDENAV DEMO http://next.materializecss.com/sidenav.html
MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
</body>
3 Days trying to figure this out :/ so any help is welcomed.
The problem is that you should initialize the side-nav in Javascript code like this
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// with jquery
$(document).ready(function(){
$('.sidenav').sidenav();
});
now your code will work perfect
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// Initialize collapsible (uncomment the lines below if you use the dropdown variation)
// var collapsibleElem = document.querySelector('.collapsible');
// var collapsibleInstance = new M.Collapsible(collapsibleElem, options);
// Or with jQuery
$(document).ready(function(){
$('.sidenav').sidenav();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><div class="user-view">
<div class="background">
<img src="images/office.jpg">
</div>
<img class="circle" src="images/yuna.jpg">
<span class="white-text name">John Doe</span>
<span class="white-text email">jdandturk#gmail.com</span>
</div></li>
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
</body>
On the materialize website, this code is given to initialize Sidenav bar
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems, options);
});
but You modify This code and remove option in var instance and now code look like and you should paste this code in your script tag or your javascript file
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
Now I explain what is the problem in upper code that given on the materialize website
in code, variable instances give 2 arguments 1st argument is elems and 2nd argument is the option that is not defined in your code so you remove the option argument in this code to solve this problem
Initialization is the most important thing when using materialize.js, for example i want to initialize a carousel.
// Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.carousel');
var instances = M.Carousel.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.carousel').carousel();
});

Switching images in a div upon hovering on a text using jQuery/Javascript

we have been given an assignment to make a div with a background image and couple of titles underneath and when you hover over a title it changes the background picture in the div ("thumbnail"). I am really new to jQuery and have no idea how to approach this. I tried the following code but it is not working.
<!DOCTYPE html>
<html lang="">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<title>Portfolio</title>
<link rel="stylesheet" href="portfolio.css">
</head>
<script>
$(function() {
$('ul a')
.mouseover(function() {
$('thumbnail').attr('src', this.getAttribute('data-image-src'));
})
.each(function() {
new Image().src = this.getAttribute('data-image-src');
});
}
</script>
<body class="body">
<!--Header-->
<header class="header">
<div class="logo">
<div class="logoimg"><img src="logo.png" width="80px" width="auto"></div>
</div>
<nav class="navbar">
About
Work
</nav>
</header>
<!--Main1-->
<div class="thumbnail"><img src="back1.jpg" width="auto" height="auto"></div>
<ul class="headlines">
link1
link2
link3
link4
</ul>
<!--Footer-->
<footer class="footer">
<p class="fotext">Copyright VĂ­tek Linhart 2017. Don't steal my shit.</p>
</footer>
</body>
</html>
I appreciate any help :)
I guess this is the thing you're looking for. Not a tested code. You've missed to say that thumbnail is a class and also it can be a hover event from jquery (check api.jquery for examples)
<script>
$(function() {
$('ul a').hover(function() {
$('.thumbnail img').attr('src', $(this).data('imageSrc'));
});
});
</script>
You can make use hover event : https://api.jquery.com/hover/
See this example as well : https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_hover
I solved it with this code. I wanted to ask though, if there is a possibility to make it animated. When the pictures switch make a fade animation.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
$('a').on('mouseover', function() {
var iSrc = $(this).attr('data-image-src');
$('.thumbnail img').attr('src', iSrc);
});
});
</script>

Javascript - image button change on click

This is my code, which I got from this site, which is confirmed as working. Not for me. Don't mind the div tag.
Paths are good, it's showing images in DW, but nothing happens after clicking on image on website...
Also, heres the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Behavioral Meta Data -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="Style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div id="container" class="container">
<ul id="scene" class="scene border fill">
<li id="Par_3" class="layer expand-width" data-depth="0.25"><img src="../Img/Par_3.svg" alt="Gallery"></li>
<li id="Par_2" class="layer expand-width" data-depth="0.20"><img src="../Img/Par_2.svg" alt="Grass_1"></li>
<li id="Par_25" class="layer expand-width" data-depth="0.20"><img src="../Img/Par_2.5.svg" alt="About me"></li>
<li id="Par_1" class="layer expand-width" data-depth="0.15"><img src="../Img/Par_1.svg" alt="Grass_2"></li>
<li id="Par_15" class="layer expand-width" data-depth="0.15"><img src="../Img/Par_1.5.svg" alt="Contact"></li>
<li id="Par_0" class="layer expand-width" data-depth="0.10"><img src="../Img/Par_0.svg" alt="Rock"></li>
<li id="Logo" class="layer expand-width" data-depth="0.05"><img src="../Img/Logo.svg" alt="Logo"></li>
</ul>
<img alt="" src="../Img/Click_u.svg" id="cm" onclick="changeImage()" />
</div>
<!-- Scripts -->
<script language="javascript">
function changeImage() {
if (document.getElementById("cm").src == "../Img/Click_u.svg")
{
document.getElementById("cm").src = "../Img/Click_ch.svg";
}
else
{
document.getElementById("cm").src = "../Img/Click_u.svg";
}
}
</script>
<script src="Parallax.js"></script>
<script>
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</body>
</html>
The thing is, .src returns not only the relative path (../Img/Click_u.svg) but the entire path (http://www.yourwebsite.com/images/Img/Click_u.svg).
So that if condition will never be true, and it will never change the image.
Perhaps try something along the lines of
if (document.getElementById("cm").src.indexOf("Click_u.svg") != -1)
To check if the snippet "Click_u.svg" can be found inside the larger string src.
Or use
document.getElementById("cm").getAttribute("src")`
and it will return you the exact value of the attribute (which is the relative path)
The code that should work on your case:
if (document.getElementById("cm").getAttribute("src") == "../Img/Click_u.svg")
{
document.getElementById("cm").src = "../Img/Click_ch.svg";
}
else
{
document.getElementById("cm").src = "../Img/Click_u.svg";
}
For some weird reason, there seems to be an invisible character just at the end of the getAttribute method. No clue as to why, but if you, reader, are willing to use this code, please retype it instead of copy-pasting.
That's a bug for another time

click event not happening with bootstrap panel

I'm trying to make my own class with panels that open and close content using Bootstrap and jQuery (not an accordion, I want multiple open at a time). However, the click event isn't working for me and I have no idea why... I tried the "*" selector and the alert was working but it's not working when I try to associate it with specific elements.
Practice2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practice 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../static/css/prism.css">
<link rel="stylesheet" href="../static/css/styles.css">
<script src="../static/js/prism.js"></script>
<script src="../static/js/script.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="panel panel-default panel-toggle" id="demo">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code><br>
Explanation
</div>
</div>
</div>
</body>
</html>
script.js
// $(".panel-toggle:panel-header").click(function(){
// // $(this).next().toggle();
// alert("hello");
// });
$("#demo").click(function(){
alert("hello");
});
styles.css
.panel-toggle .panel-heading:after {
font-family:'Glyphicons Halflings';
content:"\e114";
float: right;
color: grey;
}
.panel-toggle .collapsed:after {
content:"\e080";
}
.panel-toggle .panel-body {
}
Clearly the rest of the code needs some adjustment but I'm just troubleshooting this part right now and would appreciate some advice on what I'm missing. Thanks!
With
HTML
<div class="panel panel-default panel-toggle">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code>
Explanation
</div>
</div>
JS
$(document).ready(function(){
$(".panel-heading").click(function(){
$(this).next().toggle("slow");
});
});
works
JSFiddle demo
You should put your jQuery code in document.ready block ensure your code working after those element been generated.
Script.js should be changed like this.
$(document).ready(function(){
$("#demo").click(function(){
alert("hello");
});
});

Categories

Resources