Why does this HTML/CSS/jQuery code only work in CodePen? - javascript

This code works fine in JSFiddle, but not locally in Chrome or Firefox. Am I doing something wrong in linking the CSS or JavaScript? In the Firefox console, I get an error that $ is undefined. Am I linking jQuery improperly?
index.html:
<!DOCTYPE HTML>
<head>
<title>Digital Etch-A-Sketch</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="wrapper">
</div>
<script src="etch-a-sketch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</body>
</html>
main.css:
//Etch-A-Sketch - CSS
.square {
float: left;
height: 48px;
width: 48px;
background-color: black;
border: 1px solid white;
}
#wrapper {
position: relative;
top: 50px;
margin: 0 auto;
height: 200px;
width: 200px;
}
etch-a-sketch:
$(document).ready(function(){
var wrapper = $('#wrapper');
for (var i = 0;i < 16; i++) {
var div = $('<div class="square"></div>');
wrapper.append(div);
}
});

Include the jQuery library before you include your custom script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="etch-a-sketch.js"></script>
Otherwise you're trying to use jQuery functionality before you have library available.

JSFIDDLE DEMO
Codepen Demo
The error lies in Jquery ! you have to use .html() to inform the jquery to extract the #wrapper from the HTML document.
By the way, this also works
Jquery :
$(document).ready(function(){
for (var i = 0;i < 16; i++) {
$('#wrapper').append('<div class="square"></div>');
}
});

Related

Load stylesheet with javascript and localStorage

I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.
Desired behavior:
I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.
I have done a little test of loading it by JS with the following code (which works).
GREEN
<head>
...
<link rel="stylesheet" href="/assets/css/{{'light'}}.css">
...
</head>
This loads the CSS file called "light" as expected.
But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:
RED
<head>
...
<script>
var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
</script>
<link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
...
</head>
Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.
After that I thought that maybe creating an element would do the trick and I created one manually to test it:
RED
<head>
...
<p id="theme" style="display:none;">dark</p>
<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
And nope, the path still appears as: /assets/css/.css
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main> and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.
The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:
Click the green Preview button.
Another frame should appear on the right. Within the frame is the webpage example click the ☀️ button.
It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.
The page should still be in dark mode. 👍
/* night.css
main {
background: #000;
color: #fff;
}
*/
/* default.css */
:root {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font: 1ch/1.5 'Segoe UI';
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-size: 4ch;
}
main {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
color: #000;
}
form {
width: 80vw;
margin: 20px auto;
}
fieldset {
width: max-content;
min-height: 25px;
margin-left: auto;
padding: 0 1.5px 1.5px;
border-radius: 8px;
background: inherit;
color: inherit;
}
button {
display: block;
width: 100%;
height: 100%;
border: 0;
font-size: 4rem;
text-align: center;
background: transparent;
cursor: pointer;
}
#theme::before {
content: '☀️';
}
.night #theme::before {
content: '🌙';
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='lib/default.css' rel='stylesheet'>
<link class='night' href='lib/night.css' rel='stylesheet' disabled>
<style></style>
</head>
<body>
<main>
<form id='UI'>
<fieldset name='box'>
<legend>Theme</legend>
<button id='theme' type='button'></button>
</fieldset>
<p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
<link>`s.</p>
</form>
</main>
<script>
const UI = document.forms.UI;
const M = document.querySelector('main');
const L = document.querySelector('.night')
const switchTheme = e => {
const clk = e.target;
if (clk.matches('button')) {
M.classList.toggle('night');
L.toggleAttribute('disabled');
}
let status = M.className === 'night' ? 'on' : 'off';
localStorage.setItem('theme', status);
};
const loadTheme = e => {
let cfg = localStorage.getItem('theme');
if (cfg === 'on') {
M.classList.add('night');
L.removeAttribute('disabled');
} else {
M.classList.remove('night');
L.setAttribute('disabled', true);
}
};
UI.addEventListener('click', switchTheme);
document.addEventListener('DOMContentLoaded', loadTheme);
</script>
</body>
</html>

Infinity scroll on site using ScrollWatch.js

Trying to use ScrollWatch.js to build a web page with infinite scroll but not getting any output. Nothing is being rendered when I run my code, here is a sample of my html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Gradient Boost</title>
<link rel="stylesheet" href="{% static 'second/css/app/book.css' %}">
</head>
<body>
<h2><div data-scroll-watch>First Text</div></h2>
<h2><div data-scroll-watch>Second Text</div></h2>
<h3><div data-scroll-watch>Third Text</div></h3>
<script src="{% static 'second/js/app/book.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/scroll-watcher#latest/dist/scroll-watcher.min.js"></script>
</body>
</html>
book.js
(function() {
var addElements = function() {
var txt = document.createTextNode('Testing');
var el;
el = document.createElement('div');
el.appendChild(txt);
document.body.appendChild(el);
// If we want newly injected elements to be watched, refresh ScrollWatch. It will re-query the dom and start watching new elements.
swInstance.refresh();
};
var swInstance = new ScrollWatch({
watch: 'div',
infiniteScroll: true,
infiniteOffset: 200,
onInfiniteYInView: addElements
});
})();
and book.css
.watch-container {
font-size: 2em;
width: 75%;
height: 150px;
padding: 20px;
margin: 50px auto;
background-color: #0681CD;
color: #fff;
overflow: auto;
text-align: center;
}
div {
text-align: center;
font-size: 1em;
margin: 200px 0;
opacity: 0;
transition: opacity 1s;
font-weight: normal
}
div.scroll-watch-in-view {
opacity: 1;
}
This is the documentation I am using as guidance
Running this code on codepen seems to give me the error message in my javascript
Uncaught ReferenceError: ScrollWatch is not defined
I think your cdn link is not correct, it's scroll-watcher not scrollwatch, you can try this https://cdn.jsdelivr.net/npm/scrollwatch#2.0.1/dist/ScrollWatch-2.0.1.min.js
It works on CodePen

Overwrite styles of class using JS so change can be visible on all element with that class

someone who use JS it could be very simple.
Need to overwrite styles of one class if page is loaded in Safari browser. I think I have it all, just this line of code is problem.
This command doesnt talk to all elements with same class but it should:
document.getElementsByClassName('.background').className += " safari";
This is what I have. Mistake is in that javascript function.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
margin: 0;
padding: 0;
}
div {
margin: 10px;
background: inherit;
width: 550px;
height: 450px;
}
.background {
background: rgba(255, 20, 0, 0.3);
filter: blur(10px);
}
.safari {
background: red!important;
-webkit-backdrop-filter: blur(10px)!important;
}
</style>
</head>
<body>
<div class='background'></div>
<div></div>
<div class='background'></div>
<div></div>
<div></div>
<script type="text/javascript">
if (navigator.userAgent.indexOf('Safari') != -1 &&
navigator.userAgent.indexOf('Chrome') == -1) {
document.getElementsByClassName('background').className += " safari";
}
</script>
</body>
</html>
WHAT I TRIED
1javascript
Have also tried using same code above changing class "background" to ID "background", than in javascript part of code i changed getElementsByClassName to getElementByID - that worked but it changed only first element with that ID. Rest of elements with that ID were ignored.
2conditional comment
I have tried avoiding JS and use conditional comment following link below - both browsers use webkit so I guess this is no way.
Is there any equivalent to IE conditional comment for chrome and safari?
Thanks for help.
You need to loop through all of the elements that have that class
var bgelements = document.getElementsByClassName('background');
for(var i = 0; i < bgelements.length; i++) {
bgelements[i].className += " safari";
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
margin: 0;
padding: 0;
}
div{
margin: 10px;
background: inherit;
width: 550px;
height: 450px;
}
.background{
background: rgba(255,20,0,0.3);
filter: blur(10px);
}
.safari{
background: red!important;
-webkit-backdrop-filter: blur(10px)!important;
}
</style>
</head>
<body>
<div class='background'></div>
<div></div>
<div class='background'></div>
<div></div>
<div></div>
<script type="text/javascript">
if (navigator.userAgent.indexOf('Safari') != -1 &&
navigator.userAgent.indexOf('Chrome') == -1) {
var bgelements = document.getElementsByClassName('background');
for(var i = 0; i < bgelements.length; i++) {
bgelements[i].className += " safari";
}
}
</script>
</body>
</html>

javascript animation not showing

I have done this code with javascript to try out my first javascript animation, but when I open the page, it's showing me a blank page...
can anyone please tell me whats wrong with the code and why it's not showing anything?
thanks in advance...
<html>
<head>
<title>Trying js Animation</title>
</head>
<body>
<style>
#container{
width: 500px;
height: 500px;
color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
color: red;
position: absolute;
}
</style>
<div id="container">
<div id="box">
</div>
</div>
<script type="text/javascript">
var t = setInterval(move, 1);
var pos = 0;
var box = document.getElementById('box');
function move(){
pos += 1;
box.style.left = pos + "px";
}
</script>
</body>
</html>
The box is white. Change "color" to "background-color".

Add different styles (tagcloud/linkcloud) to hyperlinks at once

I need to create simple link display like below image;
What I thought is add separate styles for all of these links. but its looks not the best way to do this.
have anyone tried something like this? can I do this with JavaScript or JQuery?
This allows you to randomly position the Text. Maybe you could edit it slightly for your needs?
<html>
<head>
<style type='text/css'>
body {
border: 1px solid #000;
height: 300px;
margin: 0;
padding: 0;
width: 300px;
}
.box {
height: 30px;
position: absolute;
width: auto;
}
#div1 { background:0;color:red; }
#div2 { background:0;color:blue; }
#div3 { background:0; color:green;}
</style>
<script type='text/javascript'>
function setDivPos() {
for (i=1; i<=3; i++) {
var x = Math.floor(Math.random()*250);
var y = Math.floor(Math.random()*250);
document.getElementById('div'+i).style.left = x + 'px';
document.getElementById('div'+i).style.top = y + 'px';
}
}
</script>
</head>
<body onload='setDivPos();'>
<div id='div1' class='box'>one word</div>
<div id='div2' class='box'>another word</div>
<div id='div3' class='box'>and so on</div>
</body>
</html>
Anyone have time to help?
Alternative
An alternative to this would be: this demo
Links:
There are several links here that you might be interested in

Categories

Resources