HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<p>
<button id="Start">Start</button>
<button id="Clear">Clear</button>
<button id="Random">Randomize</button>
<label for="Metabolism">Metabolism</label>
<input id="Metabolism" type="text" size="3" placeholder="100"/>
</p>
<p>
This is a Backbone.js implementation of <a href="http://en.wikipedia.org/wiki/Conway_game_of_life">Conway's Game of Life</a>. On
<a href="https://github.com/SimpleAsCouldBe/gameOfLife">github</a>.
</p>
<div id="GameOfLife" class="gameOfLife"></div>
$dark: #20150C
$subtleOnDark: #30251C
$legible: #C0B5AC
$quiet: #50453C
$blue: #94BEE6
$green: #C2DD96
body
font-family: Helvetica, helvetica, 'helvetica neue', Verdana, sans-serif
line-height: 1.4
background-color: $dark
color: $legible
p
font-size: 12px
color: $quiet
margin: 0 0 10px 0
label
color: $legible
a,
a:visited
color: $quiet
br
clear: both
.gameOfLife
position: relative
line-height: 0 // Otherwise the cells stay at minimum text height apart
user-select: none
-moz-user-select: none
-webkit-user-select: none
.startBtn
margin-bottom: 10px
// The 'Living' Cells
.gameOfLife i
display: block
position: relative
background-color: $subtleOnDark
//box-shadow: 0 0 0 2px $subtleOnDark
float: left
border-radius: 7px
width: 14px
height: 14px
cursor: pointer
.running .gameOfLife i
-webkit-transition: all 0.1s ease-out
-moz-transition: all 0.1s ease-out
-transition: all 0.1s ease-out
.gameOfLife i.alive
background-color: $green
//box-shadow: 0 0 0 2px $green
z-index: 1 //live cells should be above others
.gameOfLife i:hover
background-color: $blue
//box-shadow: 0 0 0 2px $blue
z-index: 2 //hover cells should be above everyone
.gameOfLife i.alive:hover
background-color: $green + 50
box-shadow: 0 0 0 1px $green + 50
z-index: 2 //hover cells should be above everyone
// ----------------------------- The Living Cell
;(function(window, _, Backbone){
var Model, View
View = Backbone.View.extend({
tagName: 'i',
events: {
'touchstart': 'cellClicked',
'mousedown': 'cellClicked',
'mouseover': 'mouseover',
'mouseout': 'mouseout',
'touchend': 'mouseout'
},
initialize: function () {
//_.bindAll(this)
this.listenTo(this.model, 'change:isAlive', this.render)
this.render()
},
render: function () {
// Change the visual representation of aliveness
if (this.model.get('isAlive')) {
this.$el.addClass('alive')
} else {
this.$el.removeAttr('class')
}
},
mouseover: function () {
if(this.options.app.isPressing && !this.alreadyToggled) {
this.model.toggle()
this.alreadyToggled = true
}
},
mouseout: function () {
this.alreadyToggled = false
},
cellClicked: function () {
this.model.toggle()
}
})
Model = Backbone.Model.extend({
defaults: {
isAlive: false,
willLive: null,
x: null,
y: null,
size: null
},
initialize: function () {
this.neighbors = [] //Yes, I know this isn't a model property. The push syntax is too cumbersome and I don't need the eventing on neighbors
},
/**
* Given a grid of items, determine which items are adjacent to me.
* Requires that this.x and this.y be set
* @param grid a 2d array of models like this one
*/
calculateNeighbors: function (grid) {
var x = this.get('x'),
y = this.get('y')
//above
this.setNeighbor(grid, x-1, y-1)
this.setNeighbor(grid, x, y-1)
this.setNeighbor(grid, x+1, y-1)
//same level
this.setNeighbor(grid, x-1, y)
this.setNeighbor(grid, x+1, y)
//below
this.setNeighbor(grid, x-1, y+1)
this.setNeighbor(grid, x, y+1)
this.setNeighbor(grid, x+1, y+1)
//console.log('['+ this.get('x') +']['+ this.get('y') +'] has '+ this.neighbors.length +' neighbors')
},
setNeighbor: function (grid, x, y) {
if (!grid[x]) { return }
var possibleNeighbor = grid[x][y]
if (possibleNeighbor && possibleNeighbor instanceof Backbone.Model) {
this.neighbors.push( possibleNeighbor )
}
},
toggle: function () {
this.set(
'isAlive',
!this.get('isAlive')
)
},
kill: function () { this.set('willLive', false) },
birth: function () { this.set('willLive', true) },
randomize: function () {
this.set('willLive', null)
this.set('isAlive', !!(Math.round(Math.random() * 10) % 2) )
},
/**
* Look at neighbors and determine if I should stay alive, stay dead, be born, or die
*/
compete: function () {
// Get the count of live neighbors
var i, count = 0
for (i=0; i < this.neighbors.length; i++) {
if (this.neighbors[i].get('isAlive')) {
count++
}
}
// If alive
if (this.get('isAlive')) {
switch (count) {
//Any live cell with fewer than two live neighbours dies, as if caused by under-population
case 0:
case 1:
this.kill()
break
//Any live cell with two or three live neighbours lives on to the next generation
case 2:
case 3:
this.set('willLive', this.get('isAlive'))
break //stays alive
//Any live cell with more than three live neighbours dies, as if by overcrowding
case 4:
case 5:
case 6:
case 7:
case 8:
this.kill()
}
// If dead
} else {
//Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
if (count === 3) {
this.birth()
}
}
},
step: function() {
this.set('isAlive', this.get('willLive'))
this.set('willLive', null)
}
})
// Publicize
window.CellModel = Model
window.CellView = View
})(window, _, Backbone)
// ----------------------------- The Application Object
;(function(window, undefined, $, _){
var Application, _defaultMetabolism = 100
Application = Backbone.View.extend({
events: {
'touchstart': 'startPress',
'mousedown': 'startPress',
'mouseup': 'endPress',
'touchend': 'endPress'
},
startPress: function() { this.isPressing = true },
endPress: function() { this.isPressing = false },
initialize: function() {
_.bindAll(this, 'buildCells', 'toggleBtnClicked', 'cleanSlate', 'randomize', 'stop', 'start', 'live')
this.columns = this.options.columns
this.rows = this.options.rows
this.cellSize = this.options.size
this.paused = true
this.setElement('#GameOfLife')
this.buildCells()
this.render()
$('#Start').on('click', this.toggleBtnClicked)
$('#Clear').on('click', this.cleanSlate)
$('#Random').on('click', this.randomize)
},
buildCells: function () {
//console.log("Building a grid with " + this.columns + " columns and "+ this.rows +" rows")
var i, j, curModel, curView, cell2d = []
this.cells = []
// Build a new CellModel for every column & row
for (i=0; i<this.rows; i++) {
cell2d[i] = []
for (j=0; j<this.columns; j++) {
curModel = new window.CellModel({ 'x': i, 'y': j, 'size': this.cellSize })
curView = new window.CellView({ model: curModel, app: this })
cell2d[i].push( curModel )
this.cells.push( curModel )
this.$el.append( curView.el )
}
this.$el.append('<br/>')
}
// Give each cell a reference to all its neighbors
_.each(this.cells, function(cell){
cell.calculateNeighbors(cell2d)
}.bind(this))
},
toggleBtnClicked: function () {
if (this.paused) {
this.start()
} else {
this.stop()
}
},
stop: function () {
$('body').removeClass('running')
this.paused = true
$('#Start').text('Start')
},
start: function () {
$('body').addClass('running')
this.paused = false
this.metabolism = $('#Metabolism').val() || _defaultMetabolism
this.live()
$('#Start').text('Stop')
},
live: function () {
if (this.paused) { return }
// Determine what to do in the next step
_.each( this.cells, function(cell) { cell.compete() })
// Live out the next step
_.each( this.cells, function(cell) { cell.step() })
// Keep on simulating life
if (!this.paused) {
setTimeout(this.live, this.metabolism)
}
},
cleanSlate: function () {
_.each( this.cells, function(cell) { cell.kill() })
_.each( this.cells, function(cell) { cell.step() })
this.stop()
},
randomize: function () {
_.each( this.cells, function(cell) { cell.randomize() })
}
})
// Publicize
window.Application = Application
})(window, undefined, $, _)
// ----------------------------- Start the Game
;(function(window){
console.clear() // Clean up the codepen output
setTimeout(function(){
// Determine game size by Screen size
var gameOfLife,
cellSize = 14,
availWidth = window.innerWidth - 40,
availHeight = window.innerHeight - 80,
colCount = Math.floor( availWidth / cellSize ),
rowCount = Math.floor( availHeight / cellSize )
window.gameOfLife = new Application({
columns: colCount,
rows: rowCount,
size: cellSize
})
}, 200) // Timeout needed because codepen doesn't have the full doc height drawn at document.ready time
})(window)
Also see: Tab Triggers