233

This post is dedicated to testing out the newly announced Stack Snippets feature. Feel free to answer with your own Stack Snippets, and have some fun!

31
  • 134
    Plus points to whoever can find a way to abuse it? :)
    – Mysticial
    Aug 25, 2014 at 21:10
  • 2
    @Mysticial one way to find out... ;)
    – Haney StaffMod
    Aug 25, 2014 at 21:15
  • I'll have to try this out when I get home- Work won't let me run the snippet in the answer below because it's from a "Newly Registered Website" :(
    – Kendra
    Aug 25, 2014 at 21:42
  • @Kendra sounds like a workplace firewall that blocks based on content. stacksnippets.net is a newly registered domain.
    – Haney StaffMod
    Aug 25, 2014 at 21:52
  • 1
    @Haney That's what it was exactly. I'm sure it'll chill after a while. :)
    – Kendra
    Aug 25, 2014 at 23:43
  • Well, there goes PPCG. I honestly don't know if it's a good or bad thing there. Easily testable, yet obfuscated snippets :D
    – Geobits
    Aug 26, 2014 at 3:07
  • 2
    Seems like my workplace firewall is blocking most of these, which in turn then crashes my current tab, good idea, but if it is blocked at work / public networks then it's going to be a hindrance more than anything :(
    – Joe
    Aug 26, 2014 at 8:49
  • 6
    I wonder how long it will be before someone tries to write a snippet that when run applies an upvote to the containing answer (or question)...
    – JonK
    Aug 26, 2014 at 13:26
  • 1
    @JayBlanchard The snippets run fine for me in Firefox 31. Aug 26, 2014 at 13:36
  • 1
    @JayBlanchard That's good, because I was going to resort to the old "Have you tried turning it off and on again?" and I really didn't want to have to do that. Aug 26, 2014 at 19:36
  • 1
    @bfrohs you get points. I start the negotiations at whateverNumberOfPointsYouWant * -1 and let's settle in the middle?
    – Haney StaffMod
    Aug 26, 2014 at 21:04
  • 4
    I would like -9001 points please ;)
    – 0b10011
    Aug 26, 2014 at 21:05
  • 6
    Perfect, I'll counter with 9001 and we'll meet in the middle (0).
    – Haney StaffMod
    Aug 26, 2014 at 21:09
  • 1
    I don't know if it's just me, but this page takes FOREVER to load and render...
    – lc.
    Sep 9, 2014 at 5:52
  • 1
    Are the stack snippets broken? Because the server stacksnippets.net seems to have 500 server error issues. And it has been like this for a little while. Any updates on this? Jan 29, 2015 at 13:20

106 Answers 106

3

Meta-iframes - iframes within iframes

You can go (at least)  4   7   10  13 levels deep.

Each iframe's complete document is included in the srcdoc attribute. Double-quotes must be HTML-escaped as entities: " -> &quot;. The next levels of nesting require the angle-brackets to be HTML-escaped as entities as well: < -> &lt;, > -> &gt;. Each successive level of inceptionnesting requires the ampersands from each HTML-escape to be themselves HTML-escaped:

  • &quot; -> &amp;quot; -> &amp;amp;quot -> ...
  • &lt; -> &amp;lt; -> &amp;amp;lt -> ...
  • &gt; -> &amp;gt; -> &amp;amp;gt -> ...

<h1 style="text-align: center">Snippet Iframe</h1>
<iframe width="100%" height="100%" style="text-align: center" srcdoc="
  <h1 style=&quot;text-align: center&quot;>Inner Iframe 1</h1>
  <iframe width=&quot;100%&quot; height=&quot;100%&quot; srcdoc=&quot;
  &lt;h1 style=&amp;quot;text-align: center&amp;quot;&gt;Inner Iframe 2&lt;/h1&gt;
  &lt;iframe width=&amp;quot;100%&amp;quot; height=&amp;quot;100%&amp;quot; srcdoc=&amp;quot;
    &amp;lt;h1 style=&amp;amp;quot;text-align: center&amp;amp;quot;&amp;gt;Inner Iframe 3&amp;lt;/h1&amp;gt;
    &amp;lt;iframe width=&amp;amp;quot;100%&amp;amp;quot; height=&amp;amp;quot;100%&amp;amp;quot; srcdoc=&amp;amp;quot;
      &amp;amp;lt;h1 style=&amp;amp;amp;quot;text-align: center;&amp;amp;amp;quot;&amp;amp;gt;Inner Iframe 4&amp;amp;lt;/h1&amp;amp;gt;
      &amp;amp;lt;iframe width=&amp;amp;amp;quot;100%&amp;amp;amp;quot; height=&amp;amp;amp;quot;100%&amp;amp;amp;quot; srcdoc=&amp;amp;amp;quot;
        &amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;quot;&amp;amp;amp;gt;Inner Iframe 5&amp;amp;amp;lt;/h1&amp;amp;amp;gt;
        &amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;quot;
          &amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;gt;Inner Iframe 6&amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;gt;
          &amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;quot;
            &amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;gt;Inner Iframe 7&amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;gt;
            &amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;quot;
              &amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;gt;Inner Iframe 8&amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;gt;
              &amp;amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;amp;quot;
                &amp;amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;gt;Inner Iframe 9&amp;amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;amp;gt;
                &amp;amp;amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;amp;amp;quot;
                  &amp;amp;amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;gt;Inner Iframe 10&amp;amp;amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;amp;amp;gt;
				  &amp;amp;amp;amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;
                    &amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Inner Iframe 11&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
					&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;
                      &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Inner Iframe 12&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
					  &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;iframe width=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; height=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;100%&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; srcdoc=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;
                        &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;h1 style=&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;text-align: center;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Inner Iframe 13&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/h1&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
                      &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
                      &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
                    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
                    &amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
                  &amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;gt;
                  &amp;amp;amp;amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;amp;amp;amp;gt;
                &amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;gt;
                &amp;amp;amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;amp;amp;gt;
              &amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;gt;
              &amp;amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;amp;gt;
            &amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;gt;
            &amp;amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;amp;gt;
          &amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;gt;
          &amp;amp;amp;amp;lt;/iframe&amp;amp;amp;amp;gt;
        &amp;amp;amp;amp;quot;&amp;amp;amp;gt;
        &amp;amp;amp;lt;/iframe&amp;amp;amp;gt;
      &amp;amp;amp;quot;&amp;amp;gt;
      &amp;amp;lt;/iframe&amp;amp;gt;
    &amp;amp;quot;&amp;gt;
    &amp;lt;/iframe&amp;gt;
  &amp;quot;&gt;
  &lt;/iframe&gt;
&quot;>
  </iframe>
  ">
</iframe>

3

I'm debugging a Stack Snippet.

<iframe src="https://ppcg-leaderboard.xmikee.repl.co" width="100%" height="100%" style="border: none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>

3

create-react-app in SO code snippet

Use this template in your React posts! 👍

const {useState, useEffect} = React;

const App = () => {
  return (
    <div className="App">
      <header className="App-header">
        <img src="https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" className="App-logo" alt="logo" />
        <p>
          Edit code snippet and click ▶️ Run to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
};

class Root extends React.Component {
  render() {
    return (
      <App/>
    );
  }
}

ReactDOM.render(<Root />, document.getElementById('root'));
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}
.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root">
</div>

3

const date = new Date(2010, 7, 5)
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit' }) 
const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date ) 
console.log(`${day}-${month}-${year }`)

1
  • Funny watching : blinks
    – glinda93
    Jul 23, 2020 at 12:49
3

I was curious if it would be possible for a snippet to manipulate the page's UI.

Let's give it a shot:

$('body').css({
  transition: 'all 1s ease',
  transform: 'skew(0, 15deg)'
});

setTimeout(() => {
  $('body').css({
    transform: 'skew(0, 0)'
  });
}, 15000);

// Or something more nefarious?
$('[data-post-id="401649"] .js-vote-up-btn').click();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1
  • Turns out the answer is no, when embedded in an answer.
    – Cerbrus
    Sep 30, 2020 at 10:28
3

Here's a code snippet where we change code languages, in the middle of a code block. Can anyone tell how we did it?

// some harmless javascript...

document.querySelector("p.wow").style.border = "10px solid orange";

// </script>

<p>Yay! Trees are green.</p>
/* just some harmless css... */
p {
    color: red;
    background: black;
}
body {
    background: lightblue;
}
/* </style>
<!-- and look, now we have html! -->
<p class="wow">That was a big bus.</p>
<p>Hi. Purple </p>

1
  • 2
    This seemed weird until I saw the // <script> Oct 28, 2020 at 15:15
2

This probably don't matter since most everyone has pop-up block.

for (var x=0; x<5; x++) {
  window.open('https://stackoverflow.com', '_blank');
}

3
  • 10
    My console said Blocked opening 'stackoverflow.com' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.
    – bfavaretto
    Aug 26, 2014 at 0:36
  • 2
    Doesn't load anything. Chrome tells me when something is blocked, and I didn't get any dialog. Aug 26, 2014 at 0:37
  • 3
    With popups blocked, nothing happens (obviously). With popups un-blocked, I get these errors: [Error] SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent. [Error] Blocked opening 'https://stackoverflow.com/' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.
    – AstroCB
    Aug 26, 2014 at 0:39
2

You can create some simple snippet, can you edit it afterwards?

window.onload = function() {
var primes = []
for (var i=2;i<1000;i++) {
  var is_prime = true
  for (var j in primes) {
    var dvd = i / primes[j]
    if (dvd == Math.ceil(dvd)) {
      is_prime = false
      break
    }    
  }
  if (is_prime) {
    primes.push(i)
  }
}
document.getElementById('content').innerHTML = primes.toString()
}
#title {
 font-size: 14;
 font-weight: bold;
}
<div id="title">Snippet testing</div>
<div id="content">Edited for testing</div>

1
  • You're able to edit it in the normal editor view. But it doesn't copy of over when you click on the code snippet button.
    – CRABOLO
    Aug 28, 2014 at 0:38
2

Reload current page example - not work here, for the moment.

Error Message:

Uncaught SecurityError: Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "http://meta.stackoverflow.com". The frame requesting access is sandboxed and lacks the "allow-same-origin" flag.

function  ReloadPage()
{
    // not allowed any of that
    console.log(top.location.href)  ;
    top.location.replace( updateURLParameter(top.location.href, "_rnd", Math.random()) );
    return false;
}
//
// this function is an improved version of
// http://stackoverflow.com/a/10997390/159270
//
function updateURLParameter(url, param, paramVal)
{
    var TheAncor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL) 
    {
        var tmpAncor = additionalURL.split("#");
        var TheParams = tmpAncor[0];
            TheAncor = tmpAncor[1];
        if(TheAncor)
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (i=0; i<tempArray.length; i++)
        {
            if(tempArray[i].split('=')[0] != param)
            {
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }        
    }
    else
    {
        var tmpAncor = baseURL.split("#");
        var TheParams = tmpAncor[0];
            TheAncor  = tmpAncor[1];

        if(TheParams)
            baseURL = TheParams;
    }

    if(TheAncor)
        paramVal += "#" + TheAncor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  
<a href="#" onclick="return ReloadPage();">reload page</a>

2

This is really primitive. I'm sure others can do much better, but it's a minimal regex fiddle.

function run() {
  var regex = document.getElementById('regex').value;
  var haystack = document.getElementById('haystack').value;
  var ul = document.getElementById('results');
  var re = new RegExp(regex);
  var match = re.exec(haystack);
  if (match) {
    ul.innerHTML = '<li>' + match + '</li>';
  } else {
    ul.innerHTML = '<li class="missed">no match</li>';
  }
}
label {
  font-weight: bold;
}

div {
  float: left;
}

ul {
  list-style-type: none;
  margin: 0; padding: 2em;
}

li.missed {
  font-style: italic;
  color: green;
}
<div>
  <label for="regex">Regex:</label>
  <input type="text" id="regex" name="regex" value="t[aeiou]\s+m\w+h" size="40" style="padding: 4px;">
  <input type="button" id="run" value="Run" onclick="run()">
  <br>
  <textarea rows="4" cols="50" id="haystack" name="haystack">Enter text to match.</textarea>
</div>

<div>
  <ul id="results">
    <li>to match</li>
  </ul>
</div>

2

This is a little more prosaic than other answers. I wanted to see if I can run this js fiddle I used in an answer recently: http://jsfiddle.net/Ljnufjs1/

.field {
    position: absolute;
    width: 205px;
    left: 22px;
    color: #eaeaea;
}

.btn {
    line-height:40px;
    height: 35px;
    cursor: default;
    -webkit-touch-callout: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    text-align: center;
    font-size: 26px;
}

.half {
    width: 101px;
}

#register-btn {
    right:22px;
}

.green
{
    background-color:green;
}
<a href="#"><div class="field btn half green" id="register-btn">ثبت نام</div></a>

Now I have seen it in action I am very impressed.

2

See if this works.

function getTime(){
    var d = new Date();
    return [d.getHours(), d.getMinutes(), d.getSeconds()];
}

function getColor(){
    var time = getTime();
    var h = parseInt(time[0] * (0xff/24)).toString(16),
        m = parseInt(time[1] * (0xff/60)).toString(16),
        s = parseInt(time[2] * (0xff/60)).toString(16);
    return (p16(h) + p16(m) + p16(s)).toUpperCase();
}

function p10(n){// apply zero-padding if n < 10
    return n < 10 ? ('0' + n) : n;
};

function p16(n){ // p10() for hexadecimal (part of a bugfix)
    return (parseInt(n,16) < 16 ? ('0' + n) : n).toString(16);
};

(function loop(){
    var t = getTime(),
        time = [p10(t[0]),p10(t[1]),p10(t[2])],
        color = getColor(),
        face = document.getElementById("face");
    face.innerHTML = time.join(' : ') + '<hr>' + color;
    face.style.fontSize = (window.innerHeight / 6) + 'px';
    face.style.top = ((window.innerHeight / 2) - (face.clientHeight / 2))+'px';
    face.style.left = ((window.innerWidth / 2) - (face.clientWidth / 2))+'px';
    bg.style.backgroundColor = '#' + color;
    setTimeout(loop,1000);
})();
html,body{
    height:100%;
    padding:0;
    margin:0;
}

#bg{
    width:100%;
    height:100%;
    text-align:center;
}
#face{
    color:#ccccee;
    text-shadow:0px 0px 2px #000;
    font:14px arial;
    vertical-align:middle;
    position:absolute;
}
hr{
    background:#ccccee;
    border:none;
    box-shadow:0px 0px 2px #000;
    margin:10px;
    padding:1px;
}
.darken{
    position:absolute;
    left:0;
    top:0;
    padding:0;
    margin:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.2);
    background: -webkit-radial-gradient(circle, rgba(0,0,0,0), rgba(0,0,0,0.6));
    background: -moz-radial-gradient(circle, rgba(0,0,0,0), rgba(0,0,0,0.6));
    cursor:default;
}
<html>
    <div id="bg">
        <div id="face"></div>
    </div>
    <div class="darken"></div>
</html>

5
  • Well, it would appear that I have broken the sandbox. Sep 4, 2014 at 9:26
  • P.S. This is a port of the fiddle Sep 4, 2014 at 9:27
  • How do you mean "broken the sandbox"? Not sure what issue you are referring to. Sep 7, 2014 at 16:19
  • @MartinSmith At the time I made the snippet, the colors in the background were not rendering properly. Instead, it was just grey. I can see that it is working, now. So that effectively voids my earlier statement. Sep 8, 2014 at 1:40
  • Looks like the sandbox has been updated, with a snazzy new "copy code snippet" buttons, the much-requested "hide results" button, and improved CSS. Sep 8, 2014 at 1:45
2

A minor modification to Ian's test, but it highlights this is selectable text.

A minor feature request that probably wouldn't matter for most normal Q&As: the "Copy code snippet" should automatically include a reference to the original post.

@keyframes rotate {
    from {
        transform: translateZ(-300px) translateY(0px) rotateY(0deg) rotateZ(50deg) rotateX(0deg);
    }
    50% {
        transform: translateZ(-300px) translateY(0px) rotateY(180deg) rotateZ(30deg) rotateX(100deg);
    }
    to {
        transform: translateZ(-300px) translateY(0px) rotateY(360deg) rotateZ(50deg)  rotateX(0deg);
    }
}
.container {
    width: 200px;
    height: 200px;
    position: relative;
    margin: 40px auto 0 auto;
    border: 1px solid #CCC;
    perspective: 1000px;
}
#cube {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -120px;
    transform: translateZ(-100px) translateY(100px);
    transform-style: preserve-3d;
    transition: transform 1s;
    animation: rotate 2s ease-in 1s infinite;
}
#cube figure {
    display: block;
    position: absolute;
    width: 196px;
    height: 196px;
    border: 2px solid black;
    line-height: 196px;
    font-size: 120px;
    font-weight: bold;
    color: #000;
    text-align: center;
    background: rgba(255,255,255,0.5) !important;
}
#cube .front {
    background: hsla(0, 100%, 50%, 0.7);
    transform: translateZ(100px);
}
#cube .back {
    background: hsla(60, 100%, 50%, 0.7);
    transform: rotateX(-180deg) translateZ(100px);
}
#cube .right {
    background: hsla(120, 100%, 50%, 0.7);
    transform: rotateY(90deg) translateZ(100px);
}
#cube .left {
    background: hsla(180, 100%, 50%, 0.7);
    transform: rotateY(-90deg) translateZ(100px);
}
#cube .top {
    background: hsla(240, 100%, 50%, 0.7);
    transform: rotateX(90deg) translateZ(100px);
}
#cube .bottom {
    background: hsla(300, 100%, 50%, 0.7);
    transform: rotateX(-90deg) translateZ(100px);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<section class="container">
    <div id="cube" class="show-right">
        <figure class="front">F</figure>
        <figure class="back">B</figure>
        <figure class="right">R</figure>
        <figure class="left">L</figure>
        <figure class="top">U</figure>
        <figure class="bottom">D</figure>
    </div>
</section>

2

Spinning cube (CSS animation) with image and inline SVG as face.

#container {
    width:  120px;
    height: 120px;
    margin: 60px 60px;
}

#cube {
    animation: spinit 8s infinite linear;
    transform-style: preserve-3d;
    transform-origin: 60px 60px 0;
}

@keyframes spinit {
   from { transform: rotateY(0deg)   rotateX(54.735deg) rotateY(45deg); }
   to   { transform: rotateY(360deg) rotateX(54.735deg) rotateY(45deg); } 
}

#cube .face {
    position:    absolute;
    width:       120px;
    height:      120px;
    border:      1px solid black;
    background:  linear-gradient(30deg,orange,yellow,rgba(255,255,255,0.3));
    box-shadow:  inset 0 0 20px rgba(0,0,0,0.4);
    text-align:  center;
    line-height: 120px;
    color:       white;
    font-size:   80px;
    text-shadow: 2px 4px 6px blue;
}

#cube .front  { transform: rotateY(   0deg ) translateZ( 60px ); }
#cube .back   { transform: rotateY( 180deg ) translateZ( 60px ); }
#cube .right  { transform: rotateY(  90deg ) translateZ( 60px ); }
#cube .left   { transform: rotateY( -90deg ) translateZ( 60px ); }
#cube .top    { transform: rotateX(  90deg ) translateZ( 60px ); }
#cube .bottom { transform: rotateX( -90deg ) translateZ( 60px ); }
<div id="container">
    <div id="cube">
        <div class="face front">1</div>
        <!-- need to find a image with transparent background for testing -->
        <img class="face left" src="https://i.stack.imgur.com/UFoAJ.jpg?s=128&g=1"/>
        <svg class="face back"
             width="120" height="120" viewBox="0 0 120 120" 
             xmlns="http://www.w3.org/2000/svg" 
             xmlns:svg="http://www.w3.org/2000/svg" 
             xmlns:xlink="http://www.w3.org/1999/xlink">
        <defs>
            <style><![CDATA[                
                .i0, .i1, .i2, .i3, .be, .bo { stroke: black; stroke-width: 1; filter: url(#filter1);  }
                .i0      { fill:  none;    }
                .o0      { fill:  yellow;  }
                .i1, .o1 { fill:  red;     }
                .i2, .o2 { fill:  green;   }
                .i3, .o3 { fill:  blue;    }
                .be      { fill:  #ccffcc; }
                .bo      { fill:  #ccccff; }
            ]]></style>
            <filter id="filter1">
                <feGaussianBlur in="SourceAlpha" result="blur" stdDeviation="4" />
                <feSpecularLighting in="blur" lighting-color="#ffffff" result="specOut" specularConstant="0.75" specularExponent="20" surfaceScale="5">
                        <feDistantLight azimuth="240" elevation="45" />
                </feSpecularLighting>
                <feComposite in="specOut" in2="SourceAlpha" operator="in" result="specOut" />
                <feComposite in="SourceGraphic" in2="specOut" k1="0" k2="1" k3="1" k4="0" operator="arithmetic" result="litPaint" />
            </filter>
        </defs>
        <g transform="matrix( 1 0 0 -1 0 120 )">
            <circle class="i0" cx="60" cy="60" r="40" />
            <circle class="i1" cx="81" cy="60" r="19" />
            <circle class="i2" cx="49" cy="79" r="19" />
            <circle class="i3" cx="49" cy="41" r="19" />
            <circle class="o1" cx="29" cy="60" r="9" />
            <circle class="o3" cx="76" cy="87" r="9" />
            <circle class="o3" cx="27" cy="73" r="4" />
            <circle class="o2" cx="88" cy="82" r="4" />
            <circle class="o2" cx="76" cy="33" r="9" />
            <circle class="o1" cx="65" cy="95" r="4" />
            <circle class="o1" cx="65" cy="25" r="4" />
            <circle class="o3" cx="88" cy="38" r="4" />
            <circle class="o2" cx="27" cy="47" r="4" />
        </g>
        </svg>
        <div class="face right">4</div>
        <div class="face top">5</div>
        <div class="face bottom">6</div>
    </div>
</div>

  • works correctly on firefox 28.
  • needs to find a image with tranparent background to retest.

Visualizing a 3d polytope Metabiaugmented Hexagonal Prism (J56) using X3DOM.

<link href="http://www.x3dom.org/x3dom/release/x3dom.css" rel="stylesheet"/>
<script src="http://www.x3dom.org/x3dom/release/x3dom.js"></script>
<h2>metabiaugmented hexagonal prism (J56)</h2>
    <X3D xmlns="http://www.web3d.org/specifications/x3d-namespace" width="800px" height="600px">
    <Scene>
        <Viewpoint position='2.241 -8.365 5.000' orientation='0.967 0.127 0.221 1.076'></Viewpoint>
        <Background skyColor='0.671 0.804 0.937'></Background>
        <Shape>
            <Appearance>
                <Material diffuseColor='1.0 0.9 0.8' specularColor='1.0 1.0 1.0' shininess='0.7' transparency='0.15'/>
                <ImageTexture url='wood004.jpg'/>
            </Appearance>
            <IndexedFaceSet  coordIndex='12 8 3 1 5 10 -1 6 2 4 9 13 11 -1 8 12 13 9 -1 3 8 9 4 -1 5 1 2 6 -1 12 10 11 13 -1 3 0 1 -1 3 4 0 -1 1 0 2 -1 2 0 4 -1 5 7 10 -1 5 6 7 -1 10 7 11 -1 11 7 6 -1'>
                <Coordinate point='-2.608 1.022 -1.076, -1.897 0.375 0.648, -1.642 -0.697 -0.989, -1.067 1.929 -0.240, -0.812 0.857 -1.877, -0.777 -0.899 1.657, -0.522 -1.972 0.020, 0.443 -2.450 1.674, 0.883 2.210 -0.120, 1.138 1.138 -1.757, 1.172 -0.619 1.778, 1.428 -1.691 0.140, 2.003 0.935 0.889, 2.258 -0.137 -0.748,'/>
            </IndexedFaceSet> 
        </Shape>
        <Shape>
            <Appearance>
                <Material emissiveColor='0.0 0.0 0.0' specularColor='1.0 1.0 1.0' shininess='0.7'/>
            </Appearance>
            <IndexedLineSet  coordIndex='12 8 3 1 5 10 -1 6 2 4 9 13 11 -1 8 12 13 9 -1 3 8 9 4 -1 5 1 2 6 -1 12 10 11 13 -1 3 0 1 -1 3 4 0 -1 1 0 2 -1 2 0 4 -1 5 7 10 -1 5 6 7 -1 10 7 11 -1 11 7 6 -1'>
                <Coordinate point='-2.608 1.022 -1.076, -1.897 0.375 0.648, -1.642 -0.697 -0.989, -1.067 1.929 -0.240, -0.812 0.857 -1.877, -0.777 -0.899 1.657, -0.522 -1.972 0.020, 0.443 -2.450 1.674, 0.883 2.210 -0.120, 1.138 1.138 -1.757, 1.172 -0.619 1.778, 1.428 -1.691 0.140, 2.003 0.935 0.889, 2.258 -0.137 -0.748,'/>
            </IndexedLineSet> 
        </Shape>
    </Scene>
    </X3D>

  • doesn't work, why?
2
  • how do you do collapsible sections?
    – Ian
    Sep 24, 2014 at 0:36
  • @Ian To hide the snippet by default, go to the bottom of the snippet editor and select the checkbox "Hide snippet by default...". If you already have some snippet code in your answer, look for the line <!-- begin snippet: js hide: false --> and change false to true there. Sep 24, 2014 at 4:37
2

Pacman snippet

var ghostInterval, gameInterval;

var pacman = (function () {
    var names = ['inky', 'pinky', 'clyde', 'blinky'];
    var directions = Object.freeze({
        PAUZED: {
            type: 'stopped',
            sprite: 'pauzed',
            x: 0,
            y: 0
        },
        LEFT: {
            type: 'horizontal',
            sprite: 'left',
            x: -1,
            y: 0
        },
        UP: {
            type: 'vertical',
            sprite: 'top',
            x: 0,
            y: -1
        },
        RIGHT: {
            type: 'horizontal',
            sprite: 'right',
            x: 1,
            y: 0
        },
        DOWN: {
            type: 'vertical',
            sprite: 'down',
            x: 0,
            y: 1
        }
    });
    var mapObjects = {
        ' ': 'blank',
            'a': 'corner-left-top',
            'b': 'corner-right-top',
            'c': 'corner-right-bottom',
            'd': 'corner-left-bottom',
            '=': 'border-horizontal',
            '|': 'border-vertical',
            't': 'double-down',
            '>': 'left-out',
            '<': 'right-out',
            '+': 'double-right',
            '*': 'double-left',
            '1': 'left-top',
            '2': 'right-top',
            '3': 'right-bottom',
            '4': 'left-bottom',
            '8': 'single-down',
            'A': 'single-up',
            '9': 'single-vertical',
            '-': 'single-horizontal',
            '_': 'ghost-gate',
            '6': 'single-right',
            '7': 'single-left',
            'B': 'left-down',
            'C': 'down-right',
            '.': 'split-up',
            'T': 'split-down',
            '5': 'horizontal',
            'X': 'port',
            'o': 'point',
            '%': 'superball'
    };

    var level1 = [
        'a========t========b',
        '|%ooooooo9ooooooo%|',
        '|o12o152o9o152o12o|',
        '|o43o453oAo453o43o|',
        '|ooooooooooooooooo|',
        '|o67o8 6-T-7o8o67o|',
        '|%ooo9ooo9ooo9ooo%|',
        'd==bo>-7oAo6-<oa==c',
        '   |o9ooooooo9o|   ',
        '===coAoa=_=boAod===',
        'X   o o|   |o     X',
        '===bo8od===co8oa===',
        '   |o9ooooooo9o|   ',
        'a==coAo6-T-7 Aod==b',
        '|%ooooooo9ooooooo%|',
        '|o6Bo6-7oAo6-7oC7o|',
        '|oo9oooooPooooo9oo|',
        '+7 Ao8o6-T-7o8oAo6*',
        '|oooo9ooo9ooo9oooo|',
        '|o6--.-7 A 6-.--7o|',
        '|%ooooooooooooooo%|',
        'd=================c'];

    var level2 = [
        '6---T----T----T---7',
        'X   9%   9   %9   X',
        '8 8 9 12 9 12 9 8 8',
        '9 9 A 43 A 43 A 9 9',
        '9 A             A 9',
        '9   1---7 6---2   9',
        '9 8 9         9 8 9',
        '9 9 9 6-------< 9 9',
        '9 9 9         9 9 9',
        '9 9 4-------7 A 9 9',
        '9 9             9 9',
        '9 4-----7 6-----3 9',
        '9                 9',
        '4-------2 1-------3',
        '        9 9        ',
        '1-------3 4-------2',
        '9        P        9',
        '9 8 8 12 8 12 8 8 9',
        'A A 9 43 9 43 9 A A',
        'X   9%   9   %9   X',
        '6---.----.----.---7'];

    var pacman = {
        location: function (x, y) {
            if (!(this instanceof pacman.location)) {
                return new pacman.location(x, y);
            }
            this.x = x;
            this.y = y;

            pacman.location.prototype.increase = function (point) {
                if (point.x === undefined || point.y === undefined) {
                    return;
                }
                this.x += point.x;
                this.y += point.y;
            };

            pacman.location.prototype.next = function (point) {
                return new pacman.location(this.x + point.x, this.y + point.y);
            };

            pacman.location.prototype.center = function () {
                return {
                    x: this.x + 7.5,
                    y: this.y + 7.5
                };
            };

            return this;
        },
        cube: function (row, col, field, element) {
            if (!(this instanceof pacman.cube)) {
                return new pacman.cube(row, col, field);
            }
            this.row = row;
            this.col = col;
            this.left = col * 15;
            this.top = row * 15;
            this.right = this.left + 15;
            this.bottom = this.top + 15;
            this.field = field;
            this.element = element;

            this.tester = function (x, y) {
                var p = {
                    x: x,
                    y: y
                };
                return p.x >= this.left && p.x < this.right && p.y >= this.top && p.y < this.bottom;
            };

            pacman.cube.prototype.intersectsWith = function (left, right, top, bottom) {
                return this.tester(left, top) || this.tester(left, bottom) || this.tester(right, top) || this.tester(right, bottom);
            };

            return this;
        },
        point: function (row, col, field, elem) {
            if (!(this instanceof pacman.point)) {
                return new pacman.point(row, col, field);
            }
            this.row = row;
            this.col = col;
            this.left = (col * 15) + 3;
            this.top = (row * 15) + 3;
            this.right = this.left + 8;
            this.bottom = this.top + 8;
            this.element = elem;
            this.points = field === 'o' ? 50 : 100;
            this.interval = undefined;
            this.step = 0;
            this.field = field;
            this.isSuperball = field === '%';

            if (field === '%') {
                var local = this;
                this.interval = setInterval(function () {
                    local.animate();
                }, 250);
            }

            this.animate = function () {
                if (!this.element) {
                    clearInterval(this.interval);
                    return;
                }
                this.element.className = 'superball-' + (this.step % 2);
                this.step++;
                if (this.step > 100) {
                    this.step = 0;
                }
            }

            this.tester = function (x, y) {
                var p = {
                    x: x,
                    y: y
                };
                return p.x >= this.left && p.x < this.right && p.y >= this.top && p.y < this.bottom;
            };

            pacman.point.prototype.isInside = function (location) {
                var ctr = location.center();
                return this.tester(ctr.x, ctr.y);
            };

            pacman.point.prototype.remove = function () {
                if (this.interval !== undefined || this.element === undefined) {
                    clearInterval(this.interval);
                }
                if (this.element !== undefined) {
                    var fieldElement = document.getElementById('field');
                    if (fieldElement) {
                        fieldElement.removeChild(this.element);
                        this.element = undefined;
                    }
                    return this.points;
                }
                return 0;
            };

            return this;
        },
        ghost: function (x, y, element, name) {
            // make sure this always returns an object
            if (!(this instanceof pacman.ghost)) {
                return new pacman.ghost(x, y, element, name);
            }

            this.scared = 0;
            this.name = name;
            this.position = new pacman.location(x, y);
            this.direction = {
                current: directions.RIGHT,
                next: null
            };

            this.setDirection = function (new_direction) {
                // gets moved in the next iteration of the game field (user can correct if he is fast enough)
                this.direction.next = new_direction;
            };

            this.doMove = function (levelset, points) {
                this.setPosition(this.position.next(this.direction.current), levelset);
            };

            this.canMove = function (pos, levelset) {
                if (levelset === undefined)
                {
                    return false;
                }
                var left = pos.x,
                    right = pos.x + 14,
                    top = pos.y,
                    bottom = pos.y + 14;
                for (var x = 0; x < levelset.length; x++) {
                    var i = levelset[x];
                    debugger;
                    if (i.field == '_') {
                        continue;
                    }
                    if (i.intersectsWith(left, right, top, bottom)) {
                        return false;
                    }
                }
                return true;
            }

            this.getNextDirection = function (direction) {
                var s = ['left', 'right', 'up', 'down'];
                var next = Math.floor(Math.random() * s.length);
                while (direction.type == directions[s[next].toUpperCase()].type) {
                    next = Math.floor(Math.random() * s.length);
                }
                return directions[s[next].toUpperCase()];
            };

            this.setPosition = function (pos, levelset) {
                if (!this.canMove(this.position.next(this.direction.current), levelset)) {
                    this.direction.current = this.getNextDirection(this.direction.current);
                    this.direction.next = this.getNextDirection(this.direction.current);
                    return;
                }
                // no testing needed if it's not at a possible new block
                if (pos.x % 15 == 0 || pos.y % 15 == 0) {
                    if (this.direction.next !== null && this.direction.next !== undefined) {
                        if (this.canMove(pos.next(this.direction.next), levelset)) {
                            this.direction.current = this.direction.next;
                            this.direction.next = this.getNextDirection(this.direction.current);
                        }
                    }
                }
                if (pos.x < 0) {
                    pos.x += 270;
                }
                if (pos.x > 270) {
                    pos.x -= 270;
                }
                this.position = pos;
                this.playerElement.style.left = this.position.x + 'px';
                this.playerElement.style.top = this.position.y + 'px';
            };

            this.redraw = function (levelset, points) {
                var p = this;
                p.doMove(levelset, points);
                if (this.scared > 0) {
                    this.scared--;
                    p.playerElement.className = 'sprite gc ghost scared-' + (this.scared % 2);
                }
                else
                {
                    p.playerElement.className = 'sprite gc ghost ' + p.name + '-' + p.direction.current.sprite;
                }
                if (pacman.currentPlayer.isInside(p.position))
                {
                    if (this.scared > 0)
                    {
                        this.scared = 0;
                        this.position.x = 120; this.position.y = 150;
                        pacman.currentPlayer.addPoints(150);
                    }
                    else
                    {
                        var newGame = false;
                        pacman.currentPlayer.score.livesLeft--;
                        if (pacman.currentPlayer.score.livesLeft == 0)
                        {
                            newGame = true;
                            $('#txtLives').text(pacman.currentPlayer.score.livesLeft);
                            clearInterval(gameInterval);
                            clearInterval(ghostInterval);
                            alert('You have lost the game! After you click ok, the game will restart!');
                            pacman.currentPlayer = new pacman.player();
                        }
                        pacman.reset(levelset, points, newGame);
                    }
                }
            };

            this.playerElement = element;
        },
        player: function () {
            // make sure this always returns an object
            if (!(this instanceof pacman.player)) {
                return new pacman.player(arguments);
            }
            
            this.position = new pacman.location(185, 110);
            this.direction = {
                current: directions.PAUZED,
                next: null
            };
            this.score = {
                points: 0,
                livesLeft: 3,
                name: 'Player'
            };

            this.tester = function (x, y) {
                var p = {
                    x: x,
                    y: y
                };
                return p.x >= this.position.x && p.x < this.position.x + 15 && p.y >= this.position.y && p.y < this.position.y + 15;
            };
            
            this.lastLife = 0;
            this.interval = 5000;

            pacman.player.prototype.isInside = function (location) {
                var ctr = location.center();
                return this.tester(ctr.x, ctr.y);
            };

            this.setDirection = function (new_direction) {
                // gets moved in the next iteration of the game field (user can correct if he is fast enough)
                this.direction.next = new_direction;
            };

            this.doMove = function (levelset, points) {
                this.setPosition(this.position.next(this.direction.current), levelset);
                // after this move, the position should be new, and we could check if there are points to be found around us :)
                this.checkPoints(points);
            };
            
            this.addPoints = function(p) {
                this.score.points += p;
                if (this.score.points > this.lastLife + this.interval)
                {
                    this.lastLife = this.score.points;
                    this.score.livesLeft++;
                    $('#txtLives').text(this.score.livesLeft);
                }
                $('#txtScore').text(this.score.points);
            };

            this.checkPoints = function (points) {
                if (points === undefined)
                {
                    return;
                }
                var removeAt = -1;
                for (var x = 0; x < points.length; x++) {
                    var i = points[x];
                    if (i.isInside(this.position)) {
                        if (i.field === '%')
                        {
                            $(names).each(function() {
                                pacman[this].scared += 250;
                            });
                        }
                        this.addPoints(i.remove());
                        removeAt = x;
                        break;
                    }
                }
                if (removeAt >= 0) {
                    points.remove(removeAt);
                    if (points.length == 0) {
                        clearInterval(gameInterval);
                        clearInterval(ghostInterval);
                        //alert('Congratulations, you finished the level!\r\n\r\nPress F5 to restart');
                        pacman.reset();
                    }
                }
            };

            this.lastIndex = {
                row: -1,
                col: -1
            };

            this.getIndex = function (position) {
                return {
                    row: Math.floor(position.y / 15.0),
                    col: Math.floor(position.x / 15.0)
                };
            }

            this.canMove = function (pos, levelset) {
                if (levelset === undefined)
                {
                    return false;
                }
                var left = pos.x,
                    right = pos.x + 14,
                    top = pos.y,
                    bottom = pos.y + 14;
                for (var x = 0; x < levelset.length; x++) {
                    var i = levelset[x];
                    if (i.intersectsWith(left, right, top, bottom)) {
                        return false;
                    }
                }
                return true;
            }

            this.setPosition = function (pos, levelset) {
                if (this.direction.current != directions.PAUZED) {
                    if (!this.canMove(this.position.next(this.direction.current), levelset)) {
                        this.direction.current = directions.PAUZED;
                        return;
                    }
                }
                // no testing needed if it's not at a possible new block
                if (pos.x % 15 == 0 || pos.y % 15 == 0) {
                    if (this.direction.next !== null && this.direction.next !== undefined) {
                        if (this.direction.next == directions.PAUZED) {
                            this.direction.current = directions.PAUZED;
                            this.direction.next = null;
                        } else {
                            if (this.canMove(pos.next(this.direction.next), levelset)) {
                                this.direction.current = this.direction.next;
                                this.direction.next = null;
                            }
                        }
                    }
                }
                if (levelset === undefined)
                {
                    return;
                }
                if (pos.x < 0) {
                    pos.x += 270;
                }
                if (pos.x > 270) {
                    pos.x -= 270;
                }
                this.position = pos;
                this.playerElement.style.left = this.position.x + 'px';
                this.playerElement.style.top = this.position.y + 'px';
            };

            var animation = 0,
                adir = 0.1,
                lastani = -1;

            this.redraw = function (levelset, points) {
                var p = this;
                p.doMove(levelset, points);
                var i = parseInt(animation) % 3;
                if (i != lastani) {
                    lastani = i;
                    p.playerElement.className = 'sprite gc pacman-' + p.direction.current.sprite.toLowerCase() + '-' + i;
                }
                animation += adir;
                if (animation == 2 || animation == 0) {
                    adir *= -1;
                }
            };

            this.playerElement = document.getElementById('player');
        },
        level: function (description, points) {
            var fieldElement = document.getElementById('field');
            var height = description.length;
            var arr = [],
                pf = [];
            for (var y = 0; y < height; y++) {
                var row = description[y];
                var width = row.length;
                for (var x = 0; x < width; x++) {
                    var field = row.charAt(x);
                    if (field === 'P') {
                        pacman['currentPlayer'].setPosition(pacman.location(x * 15, y * 15), arr);
                        continue;
                    }
                    if (field === 'o' || field === '%') {
                        // point to eat or superball
                        if (points !== undefined && points.length > 0) {
                            continue;
                        }
                        var point = document.createElement('div');
                        point.className = mapObjects[field];
                        point.style.left = ((x * 15) + 3) + 'px';
                        point.style.top = ((y * 15) + 3) + 'px';
                        point.style.width = '8px';
                        point.style.height = '8px';
                        fieldElement.appendChild(point);
                        pf.push(new pacman.point(y, x, field, point));
                        continue;
                    }
                    var classname = mapObjects[field];
                    if (classname === "undefined" || classname === "null" || classname === "blank") {
                        continue;
                    }
                    var block = document.createElement('div');
                    block.className = 'sprite gc ' + classname;
                    block.style.left = (x * 15) + 'px';
                    block.style.top = (y * 15) + 'px';
                    block.style.width = '15px';
                    block.style.height = '15px';
                    fieldElement.appendChild(block);
                    if (field == 'X') {
                        // pacman can run through ports
                        continue;
                    }
                    arr.push(new pacman.cube(y, x, field, block));
                }
            }
            return {
                blocks: arr,
                points: points !== undefined && points.length > 0 ? points : pf
            };
        },
        onKeydown: function (e) {
            var p = pacman['currentPlayer'];
            var handled = true;
            if (e.key !== undefined && e.key !== null) {
                switch (e.key) {
                    case 'Up':
                        p.setDirection(directions.UP);
                        break;
                    case 'Down':
                        p.setDirection(directions.DOWN);
                        break;
                    case 'Left':
                        p.setDirection(directions.LEFT);
                        break;
                    case 'Right':
                        p.setDirection(directions.RIGHT);
                        break;
                    default:
                        handled = false;
                        break;
                }
                if (handled) {
                    return;
                }
            }
            handled = true;
            switch (e.keyCode) {
                case 80:
                    p.direction.current = directions.PAUZED;
                    break;
                case 82:
                    p.direction.current = directions.PAUZED;
                    break;
                case 38:
                    p.setDirection(directions.UP);
                    break;
                case 40:
                    p.setDirection(directions.DOWN);
                    break;
                case 37:
                    p.setDirection(directions.LEFT);
                    break;
                case 39:
                    p.setDirection(directions.RIGHT);
                    break;
                default:
                    handled = false;
                    break;
            }
        },
        start: function (points) {
            var animation = 0,
                direction = 1;
            if (pacman['currentPlayer'] === undefined) {
                pacman['currentPlayer'] = new pacman.player();
            }
            $('#txtScore').text(pacman.currentPlayer.score.points);
            $('#txtLives').text(pacman.currentPlayer.score.livesLeft);
            var levelset = pacman.level(level1, points);
            gameInterval = setInterval(function () {
                try {
                    if (levelset === undefined)
                    {
                        clearInterval(gameInterval);
                        return;
                    }
                    pacman.currentPlayer.redraw(levelset.blocks, levelset.points);
                } catch (ex) { console.log(ex); }
            }, 5);
            for (var x = 0; x < 4; x++) {
                var g = document.createElement('div');
                g.className = 'sprite gc ghost ' + names[x] + '-right';
                g.style.position = 'absolute';
                g.style.left = '120px';
                g.style.top = '150px';
                g.style.width = '15px';
                g.style.height = '15px';
                var fe = document.getElementById('field');
                fe.appendChild(g);
                pacman[names[x]] = new pacman.ghost(120, 150, g, names[x]);
            }
            ghostInterval = setInterval(function () {
                $(names).each(function () {
                    var p = pacman[this];
                    if (p === undefined)
                    {
                        clearInterval(ghostInterval);
                        return;
                    }
                    p.redraw(levelset.blocks, levelset.points);
                });
            }, 5);
        },
        reset: function(blocks, points, isNewGame) {
            clearInterval(ghostInterval);
            clearInterval(gameInterval);
            var fd = document.getElementById('field');
            $(blocks).each(function() {
                fd.removeChild(this.element);
            });
            blocks.splice(0, blocks.length);
            if (isNewGame)
            {
                $(points).each(function() {
                    fd.removeChild(this.element);
                });
                points.splice(0, points.length);
            }
            $('.ghost').each(function() {
                fd.removeChild(this);
            });
            $(names).each(function() {
                pacman[this] = undefined;
            });
            pacman.start(points);
        }
    };

    return pacman;
})();

Array.prototype.remove = function (index) {
    this.splice(index, 1);
}

$(function () {
    $(document).keydown(pacman.onKeydown);
    pacman.start();
});
    html {
        font-family:'Verdana';
        font-size: 1em;
    }
    body {
        background: #000000;
        overflow: hidden;
        margin: 0;
        padding: 0;
    }
    h1 {
        line-height: 1em;
        font-size: 3em;
        padding: 0;
        margin: 0;
        text-align: center;
        color: yellow;
        text-decoration: none;
    }
    small {
        color: #777777;
        font-style: italic;
        text-align: center;
        display: block;
        margin: 0;
        padding: 0;
    }
    #game {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
    #console {
        color: #ffffff;
    }
    .sprite {
        background-image: url('http://i50.tinypic.com/16c2nux.png');
        width: 16px;
        height: 16px;
    }
    .gc {
        position: absolute;
        display: inline-block;
        /*background-color: #000000;*/
        margin: 0;
        padding: 0;
        /*border: solid #cfcfcf 1px;*/
    }
    .console {
        color: #ffffff;
    }
    .blank {
        background: #000000;
    }
    .port {
        background: #000000;
        z-index: 4;
    }
    .border-vertical {
        background-position: -1px -18px;
    }
    .corner-left-top {
        background-position: -1px -1px;
    }
    .border-horizontal {
        background-position: -19px -1px;
    }
    .corner-right-top {
        background-position: -221px -1px;
    }
    .corner-right-bottom {
        background-position: -41px -153px;
    }
    .corner-left-bottom {
        background-position: -1px -245px;
    }
    .double-down {
        background-position: -111px -1px;
    }
    .left-out {
        background-position: -63px -80px;
    }
    .right-out {
        background-position: -159px -80px;
    }
    .double-right {
        background-position: -1px -200px;
    }
    .double-left {
        background-position: -221px -200px;
    }
    .left-top {
        background-position: -21px -23px;
    }
    .right-top {
        background-position: -44px -23px;
    }
    .right-bottom {
        background-position: -44px -38px;
    }
    .left-bottom {
        background-position: -21px -38px;
    }
    .horizontal {
        background-position: -30px -38px;
    }
    .single-down {
        background-position: -63px -56px;
    }
    .single-up {
        background-position: -63px -105px;
    }
    .single-vertical {
        background-position: -63px -62px;
    }
    .single-horizontal {
        background-position: -78px -80px;
    }
    .ghost-gate {
        background-position: -111px -101px;
    }
    .single-right {
        background-position: -134px -80px;
    }
    .single-left {
        background-position: -92px -80px;
    }
    .left-down {
        background-position: -39px -176px;
    }
    .down-right {
        background-position: -183px -176px;
    }
    .split-up {
        background-position: -63px -224px;
    }
    .split-down {
        background-position: -111px -56px;
    }
    .ghost {
        z-index: 3;
    }
    .inky-left {
        background-position: -239px -9px;
    }
    .inky-right {
        background-position: -290px -9px;
    }
    .inky-top {
        background-position: -256px -9px;
    }
    .inky-down {
        background-position: -273px -9px;
    }
    .clyde-left {
        background-position: -239px -25px;
    }
    .clyde-right {
        background-position: -290px -25px;
    }
    .clyde-top {
        background-position: -256px -25px;
    }
    .clyde-down {
        background-position: -273px -25px;
    }
    .pinky-left {
        background-position: -239px -41px;
    }
    .pinky-right {
        background-position: -290px -41px;
    }
    .pinky-top {
        background-position: -256px -41px;
    }
    .pinky-down {
        background-position: -273px -41px;
    }
    .scared-0 {
        background-position: -256px -74px;
    }
    .scared-1 {
        background-position: -273px -74px;
    }
    .blinky-left {
        background-position: -239px -58px;
    }
    .blinky-right {
        background-position: -290px -58px;
    }
    .blinky-top {
        background-position: -256px -58px;
    }
    .blinky-down {
        background-position: -273px -58px;
    }
    #field {
        position: absolute;
        left: 50%;
        margin-left: -142.5px;
        top: 50%;
        margin-top: -172.5px;
        width: 285px;
        height: 345px;
    }
    #player {
        z-index: 3;
    }
    .pacman, .pacman-left-0, .pacman-top-0, .pacman-down-0, .pacman-right-0, .pacman-pauzed-0, .pacman-pauzed-1, .pacman-pauzed-2 {
        background-position: -269px -163px;
    }
    .pacman-left-1 {
        background-position: -253px -163px;
    }
    .pacman-left-2 {
        background-position: -237px -163px;
    }
    .pacman-top-1 {
        background-position: -269px -147px;
    }
    .pacman-top-2 {
        background-position: -268px -131px;
    }
    .pacman-right-1 {
        background-position: -285px -163px;
    }
    .pacman-right-2 {
        background-position: -301px -163px;
    }
    .pacman-down-1 {
        background-position: -269px -179px;
    }
    .pacman-down-2 {
        background-position: -269px -195px;
    }
    .point, .superball-0, .superball-1 {
        width: 8px;
        height: 8px;
        background-image: url('http://i50.tinypic.com/16c2nux.png');
        position: absolute;
    }
    .point, .superball, .superball-0 {
        background-position: -291px -78px;
    }
    .superball-1 {
        background-position: -300px -79px;
    }
    .scoreboard {
        border-spacing: 1px 1px;
        background-color: #000000;
        font-family:'Helvetica';
        font-variant: small-caps;
        text-transform: lowercase;
        width: 100%;
        position: absolute;
        top: -35px;
        left: 0px;
        right: 0px;
        font-size: 12px;
        letter-spacing: 1px;
    }
    .scoreboard td {
        padding-top: 1px;
        padding-bottom: 1px;
        padding-left: 5px;
        padding-right: 5px;
        background-color: #999999;
        color: #000000;
        text-align: center;
        width: 50%;
    }
    .scoreboard td.title {
        font-weight: 800;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="game">
     <h1>PACMAN</h1>
 <small>Sprites &copy; Super Goomba-Rio</small>

    <div id="field">
        <table class="scoreboard" id="scoreboard">
          <tr><td class="title">SCORE:</td><td class="title">Lifes</td></tr>
          <tr><td id="txtScore" align="right">0</td><td id="txtLives" align="center">3</td></tr>
        </table>
        <div id="player" class="sprite gc pacman"></div>
    </div>
</div>

Kinda late, but I thought why not

2

This is a leaderboard example for this question. If you want to suggest a leaderboard as a comment, here's a comment template:

May I suggest a leaderboard for this post? [Here's](https://meta.stackoverflow.com/questions/269754/stack-snippets-sandbox-try-it-out-here/384473#384473) an example, and [here's](https://xmikee1.github.io/ppcg-leaderboard/implement) how to implement the leaderboard.

Leaderboard

You can view the leaderboard for this post by expanding the widget/snippet below. In order for your post to be included in the rankings, you need a header (# header text) with the following info:

  • The name of the language (end it with a comma , or dash -), followed by...

  • The byte count, as the last number to appear in your header.

For example, JavaScript (ES6), 72 bytes is valid, but Fortran, 143 bytes (8-bit) is invalid because the byte count is not the last number in the header (your answer will be recognized as 8 bytes - don't take advantage of this).

<iframe src="https://xmikee1.github.io/ppcg-leaderboard/?id=183544" width="100%" height="100%" style="border: none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>

2

If you want to check if localStorage works in snippet

try {
  const expected = 'minatozaki sana';
  let message = 'Testing localStorage...';
  window.localStorage.setItem('name', expected);
  const actual = window.localStorage.getItem('name');
  if (actual === expected) {
     message = 'localStorage does work in SO snippet';
  } else {
     message = `localStorage still does not work in SO snippet, expected '${expected}' but got: '${actual}'`;
  }

} catch (e) {
  message = `localStorage still does not work in SO snippet, threw exception:\n ${e}`;
}
document.getElementById('result').innerText = message;
<div id="result">
Testing localStorage...
</div>

4
  • 1
  • 1
    Allowing local storage in code snippets is quite dangerous. I was just curious to see if it works now.
    – glinda93
    Jun 9, 2020 at 12:36
  • Cool, just wanted to let you know that the lack of capability is a known issue :). Jun 9, 2020 at 12:41
  • 2
    I already knew that. Turns out this is such an old question. I thought it was new one, because it showed up at the top of my question list. Thought a new feature just has been introduced. Meh...
    – glinda93
    Jun 9, 2020 at 12:44
2

A sham for the Storage API that uses a Map backer and does not survive refresh (since Stack Snippets don't survive refresh). Might help with basic questions about the Storage API regarding serialization, or getting/setting values.

Can be included in Stack Snippets by including the following GitHub/JSDelivr script HTML:

<script src="https://cdn.jsdelivr.net/gh/mikemccaughan/heretic-monkey.link/FauxStorage.js"></script>

// You can get/set using standard property-like getters and setters
localStore.test = 'value';
// They are separate stores 
console.log('sessionStore does not have a test key, so it returns null: ', sessionStore.test, `(${typeof sessionStore.test})`);
// You can get/set using Storage API
console.log(`localStore.getItem('test'):`, localStore.getItem('test'), `(${typeof localStore.test})`);
// stores only the string of the value
sessionStore.setItem('test', 123);
console.log(sessionStore.test, `(${typeof sessionStore.test})`);
sessionStore.test = {
  a: 'b'
};
console.log(sessionStore.test, `(${typeof sessionStore.test})`);
localStore.test = ['a', 1, {
  index: 2
}];
console.log(localStore.test, `(${typeof localStore.test})`);
// setting the value to null sets it to the string "null"
localStore.test = null;
console.log(localStore.test, `(${typeof localStore.test})`);
// setting the value to undefined sets it to the string "undefined"
localStore.test = undefined;
console.log(localStore.test, `(${typeof localStore.test})`);
// removing the item is the way to clear the value for the specific key (and it returns null when not found)
localStore.removeItem('test');
console.log(localStore.test, `(${typeof localStore.test}) <- note the type is object, since typeof null === 'object'`);
<script src="https://cdn.jsdelivr.net/gh/mikemccaughan/heretic-monkey.link/FauxStorage.js"></script>

The actual code for those interested:

// A sham for the Storage API that uses a `Map` backer and does not survive refresh 
// (since Stack Snippets don't survive refresh). Might help with basic questions about 
// the Storage API regarding serialization, or getting/setting values.
//
// Note you'll need to use localStore instead of localStorage and sessionStore instead 
// of sessionStorage to use the shams.

class FauxStorage {
  // private class fields do not have wide support as of this writing
  // #store = new Map();
  constructor() {
    let self = this;
    self.store = new Map();
    return new Proxy(this, {
      get(target, prop) {
        if (!(prop in target)) {
          return target.getItem(prop);
        }

        return target[prop];
      },
      set(target, prop, value) {
        if (!(prop in target)) {
          target.setItem(prop, value);
          return true;
        }

        return false;
      },
      getOwnPropertyDescriptor(target, prop) {
        return prop in target ? {
          value: target[prop],
          writable: false,
          enumerable: false,
          configurable: false
        } : {
          value: target.getItem(prop),
          writable: true,
          enumerable: true,
          configurable: true
        };
      }
    });
  }
  get length() {
    return this.store.size;
  }
  getItem(key) {
    return this.store.get(key) ?? null;
  }
  setItem(key, value) {
    this.store.set(key, String(value));
  }
  removeItem(key) {
    this.store.delete(key);
  }
  key(index) {
    return [...this.store.keys()][index];
  }
  clear() {
    this.store.clear();
  }
}
(function() {
  // Note: Requires new names because sandbox attribute on iframe denies access to localStorage/sessionStorage name, regardless of implementation.
  window.localStore = new FauxStorage();
  window.sessionStore = new FauxStorage();
})();
1

    //Made for Stack Overflow Code Testing

    //Unicorn Inspired by http://drbl.in/kayh

    //Made by Mr. Alien


    /*
     * Just created in a hurry, so won't refactor my CSS
     * as of now, also I can drastically reduce
     * the markup but I won't do it right now
    */
    html, body {
      height: 450px;
      background: -webkit-radial-gradient(center, ellipse, #fce300 0%, #ffc700 46%, #ff7f00 100%);
      background: radial-gradient(ellipse at center, #fce300 0%,#ffc700 46%,#ff7f00 100%);
    }

    .unicorn {
      position: absolute;
      left: 50%;
      top: 170px;
      margin-left: -250px;
    }

    .tail > div,
    .body > div,
    .leg > div,
    .leg2 > div,
    .leg3 > div,
    .unihorn {
      width: 0; 
      height: 0;
      position: absolute;
      -webkit-transform-origin: 50% 50%;
          -ms-transform-origin: 50% 50%;
              transform-origin: 50% 50%;
    }

    .tail .pone{ 
      border-left: 30px solid transparent;
      border-right: 40px solid transparent;
      border-bottom: 30px solid #ffb82b;
      -webkit-transform: rotate(6deg);
          -ms-transform: rotate(6deg);
              transform: rotate(6deg);
    }

    .tail .ptwo {
      border-left: 40px solid transparent;
      border-right: 30px solid transparent;
      border-bottom: 30px solid #FD8A07;
      -webkit-transform: rotate(-39deg);
          -ms-transform: rotate(-39deg);
              transform: rotate(-39deg);
      top: 26px;
      left: -30px;
    }

    .tail .pthree {
      border-top: 30px solid transparent;
      border-bottom: 30px solid transparent; 
      border-right: 30px solid #ffb82b; 
      -webkit-transform: rotate(5deg); 
          -ms-transform: rotate(5deg); 
              transform: rotate(5deg);
      top: 45px;
      left: -12px;
    }

    .tail .pfour {
      top: 72px;
      left: 17px;
      border-bottom: 35px solid #FD8A07;
      border-right: 35px solid transparent;
      -webkit-transform: rotate(5deg);
          -ms-transform: rotate(5deg);
              transform: rotate(5deg);
    }

    div.body .pone {
      border-top: 10px solid transparent;
      border-left: 221px solid #FD8A07;
      border-bottom: 60px solid transparent;
      -webkit-transform: rotate(40deg);
          -ms-transform: rotate(40deg);
              transform: rotate(40deg);
      top: 65px;
      left: 45px;
    }

    div.body .ptwo {
      border-bottom: 70px solid #ffb82b;
      border-left: 90px solid transparent;
      border-right: 130px solid transparent;
      -webkit-transform: rotate(43deg);
          -ms-transform: rotate(43deg);
              transform: rotate(43deg);
      top: 15px;
      left: 87px;
    }

    div.body .pthree {
      border-bottom: 100px solid #FD8A07;
      border-left: 20px solid transparent;
      border-right: 130px solid transparent;
      -webkit-transform: rotate(71deg);
          -ms-transform: rotate(71deg);
              transform: rotate(71deg);
      top: 15px;
      left: 200px;
    }

    div.body .pfour {
      border-bottom: 100px solid #ffb82b;
      border-left: 30px solid transparent;
      border-right: 130px solid transparent;
      -webkit-transform: rotate(109deg);
          -ms-transform: rotate(109deg);
              transform: rotate(109deg);
      top: 38px;
      left: 246px;
    }

    div.body .pfive {
      border-bottom: 60px solid #FD8A07;
      border-right: 105px solid transparent;
      left: 310px;
      top: -27px;
      -webkit-transform: rotate(34deg);
          -ms-transform: rotate(34deg);
              transform: rotate(34deg);
    }

    div.body .psix {
      border-top: 85px solid #ffb82b;
      border-left: 85px solid transparent;
      left: 319px;
      top: -40px;
      -webkit-transform: rotate(19deg);
          -ms-transform: rotate(19deg);
              transform: rotate(19deg);
    }

    div.body .pseven {
      border-bottom: 110px solid #FD8A07;
      border-left: 85px solid transparent;
      left: 350px;
      top: -144px;
      -webkit-transform: rotate(19deg);
          -ms-transform: rotate(19deg);
              transform: rotate(19deg);
    }

    div.body .peight {
      border-bottom: 90px solid #ffb82b;
      border-right: 120px solid transparent;
      left: 425px;
      top: -92px;
      -webkit-transform: rotate(18deg);
          -ms-transform: rotate(18deg);
              transform: rotate(18deg);
    }

    div.body > div.eye {
      background-color: #000;
      top: -70px;
      left: 445px;
      height: 10px;
      width: 10px;
      border-radius: 50%;
      z-index: 1;
    }

    div.nose {
      border-bottom: 40px solid #f27d00;
      border-right: 40px solid transparent;
      -webkit-transform: rotate(-28deg);
          -ms-transform: rotate(-28deg);
              transform: rotate(-28deg);
      left: 480px;
      top: -15px;
    }

    div.extreme-left {
      border-top: 115px solid transparent;
      border-right: 30px solid #ffb82b;
      border-bottom: 110px solid transparent;
      -webkit-transform: rotate(-65deg);
          -ms-transform: rotate(-65deg);
              transform: rotate(-65deg);
      left: 130px;
      top: 4px;
    }

    div.leg .pone {
      border-top: 120px solid transparent;
      border-right: 60px solid #FD8A07;
      border-bottom: 0px solid transparent;
      -webkit-transform: rotate(-50deg);
          -ms-transform: rotate(-50deg);
              transform: rotate(-50deg);
      top: 55px;
      left: 45px; 
    }

    div.leg .ptwo {
      border-top: 20px solid transparent;
      border-right: 30px solid #ffb82b;
      border-bottom: 20px solid transparent;
      top: 145px;
      -webkit-transform: rotate(-24deg);
          -ms-transform: rotate(-24deg);
              transform: rotate(-24deg);
      left: 66px;
    }

    div.leg .pthree {
      border-top: 15px solid transparent;
      border-right: 33px solid #FD8A07;
      border-bottom: 20px solid transparent;
      top: 164px;
      -webkit-transform: rotate(34deg);
          -ms-transform: rotate(34deg);
              transform: rotate(34deg);
      left: 63px;
    }

    div.leg .pfour {
      border-left: 0 solid transparent;
      border-right: 20px solid transparent;
      border-bottom: 100px solid #ffb82b;
      -webkit-transform: rotate(-15deg);
          -ms-transform: rotate(-15deg);
              transform: rotate(-15deg);
      top: 165px;
      left: 80px;
    }

    div.leg .pfive {
      border-bottom: 30px solid #FD8A07;
      border-right: 30px solid transparent;
      top: 235px;
      -webkit-transform: rotate(-15deg);
          -ms-transform: rotate(-15deg);
              transform: rotate(-15deg);
      left: 89px;
    }

    div.body .extreme-right {
      left: 246px;
      top: 100px;
      border-top: 30px solid #FD8A07;
      border-left: 80px solid transparent;
      border-right: 85px solid transparent;
      -webkit-transform: rotate(-33deg);
          -ms-transform: rotate(-33deg);
              transform: rotate(-33deg);
    }

    div.leg2 div.pone {
      border-top: 50px solid #ffb82b;
      border-right: 85px solid transparent;
      left: 339px;
      top: 84px;
      -webkit-transform: rotate(-53deg);
          -ms-transform: rotate(-53deg);
              transform: rotate(-53deg);
    }

    div.leg2 div.ptwo {
      border-bottom: 20px solid #FD8A07;
      border-left: 42px solid transparent;
      border-right: 30px solid transparent;
      -webkit-transform: rotate(62deg);
          -ms-transform: rotate(62deg);
              transform: rotate(62deg);
      left: 328px;
      top: 146px;
    }

    div.leg2 .pthree {
      border-left: 0 solid transparent;
      border-right: 20px solid transparent;
      border-bottom: 100px solid #ffb82b;
      -webkit-transform: rotate(-15deg);
          -ms-transform: rotate(-15deg);
              transform: rotate(-15deg);
      top: 154px;
      left: 368px;
    }

    div.leg2 .pfour {
      border-bottom: 30px solid #FD8A07;
      border-right: 30px solid transparent;
      top: 230px;
      -webkit-transform: rotate(-15deg);
          -ms-transform: rotate(-15deg);
              transform: rotate(-15deg);
      left: 378px;
    }

    div.leg3 div.pone {
      border-top: 50px solid transparent;
      border-left: 60px solid #ef7b00;
      border-bottom: 30px solid transparent;
      left: 382px;
      top: 60px;
      -webkit-transform: rotate(6deg);
          -ms-transform: rotate(6deg);
              transform: rotate(6deg);
    }

    div.leg3 div.ptwo {
      border-left: 0px solid transparent;
      border-right: 30px solid transparent;
      border-top: 50px solid #e87604;
      left: 419px;
      top: 116px;
      -webkit-transform: rotate(-18deg);
          -ms-transform: rotate(-18deg);
              transform: rotate(-18deg);
    }

    div.leg3 div.pthree {
      border-bottom: 30px solid #e5892d;
      border-left: 13px solid transparent;
      left: 411px;
      top: 143px;
      -webkit-transform: rotate(-17deg);
          -ms-transform: rotate(-17deg);
              transform: rotate(-17deg);
    }

    div.leg3 .pfour {
      border-bottom: 30px solid #FD8A07;
      border-right: 30px solid transparent;
      top: 173px;
      -webkit-transform: rotate(76deg);
          -ms-transform: rotate(76deg);
              transform: rotate(76deg);
      left: 403px;
    }

    .unihorn {
      top: -130px;
      left: 446px;
      border-top: 10px solid transparent;
      border-left: 120px solid #FD8A07;
      border-bottom: 10px solid transparent;
      -webkit-transform: rotate(-36deg);
          -ms-transform: rotate(-36deg);
              transform: rotate(-36deg);
    }
    <div class="unicorn">
      <div class="tail">
        <div class="pone"></div>
        <div class="ptwo"></div>
        <div class="pthree"></div>
        <div class="pfour"></div>
      </div>
      <div class="body">
        <div class="pone"></div>
        <div class="ptwo"></div>
        <div class="pthree"></div>
        <div class="pfour"></div>
        <div class="pfive"></div>
        <div class="psix"></div>
        <div class="pseven"></div>
        <div class="peight"></div>
        <div class="eye"></div>
        <div class="nose"></div>
        <div class="extreme-left"></div>
        <div class="extreme-right"></div>
      </div>
      <div class="leg">
        <div class="pone"></div>
        <div class="ptwo"></div>
        <div class="pthree"></div>
        <div class="pfour"></div>
        <div class="pfive"></div>
      </div>
      <div class="leg2">
        <div class="pone"></div>
        <div class="ptwo"></div>
        <div class="pthree"></div>
        <div class="pfour"></div>
      </div>
      <div class="leg3">
        <div class="pone"></div>
        <div class="ptwo"></div>
        <div class="pthree"></div>
        <div class="pfour"></div>
      </div>
      <div class="unihorn"></div>
    </div>

1

$(document).ready(function() {
  $.get('http://crossorigin.me/http://php.net/', function(data) {
    var $php = $(data), rcs = [], ver = 0, num = 0, i = 0, time;
    $php.find('h2.newstitle > a').each(function() {
      var txt = $(this).text();
      var matches = /([\d.]+) (RC ([\d.]+))?/.exec(txt);
      if(matches) {
        time = $(this).parent().parent().find('time').text();
        if(matches[2]) {
          ver = matches[1];
          if(matches[3] > num) num = matches[3];
        } else {
          $('#php').prepend($('<div style="white-space: pre;"></div>').html((i++ === 2 ? '<b>Current' : '<b>Old') + ' Stable Version:</b> ' + matches[1] + ' // Release Date: ' + time));
        }
      }
    });
    $('#php').append($('<div></div>').html('<b>Next Stable Version:</b> ' + ver + ' RC ' + num + ' \t\t// Release Date: ' + time));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="php"></div>

1

function DemoController($scope) {
  
  $scope.items = [
    { access: 'TuChanca' },
    { access: 'SomethingElse' },
  ];
  
  $scope.isRowDisabled = function(item) {
    // Return true to apply 'off' class
    return !validateItem(item);
  };
    
  $scope.onRowClick = function(item) {
    if (validateItem(item)) {
      alert('Row has been click');
    }
  };
    
  function validateItem(item) {
    // Return true if item is clickable
    return item.access === 'TuChanca';
  }
}
.row {
  border: 1px solid #cccccc;
  background: #fafafa;
  color: rgba(0,0,0,0.87);
  padding: 10px;
}

.row:not(.off):hover {
  cursor: pointer;
  background: rgba(0,0,0,0.07);
}

.row.off {
  color: rgba(0,0,0,0.5);
  cursor: not-allowed;
}
<html ng-app>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller='DemoController'>

  <div class="row"
       ng-repeat="item in items" 
       ng-class="{ 'off': isRowDisabled(item) }"
       ng-click="onRowClick(item)">
    {{ item.access }}
  </div>
  
</body>
</html>

1

This concerns Merge two array of objects based on a key.

Below, notice how id: "abdc4051" is the first item in the arr1 array,
but the second item in the arr2 array. (!)

function merge(array,key){
    let map = {};
    array.forEach(val=>{
        if(map[val[key]]){
            map[val[key]] = {...map[val[key]],...val};
        }else{
            map[val[key]] = val;
        }
    })
    return Object.keys(map).map(val=>map[val]);
}
let arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
];
let arr2 = [
  { id: "abdc4052", name: "abc" },
  { id: "abdc4051", name: "ab"  }
];

document.write(JSON.stringify(merge( [...arr1,...arr2], 'id')));

The result is still the same. (Hooray!)

0

span {
  margin: 5px;
  padding: 5px;
  border:2px solid;
  color: red;
  border-radius:50%;
}
Hello World<br />
<span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span><span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

1
0

Testing a bug with Chrome (at least in macOS) where requestAnimationFrame fires far faster than screen refresh rate when scrolling if another Stack Snippet is running.

I unfortunately can't make a min-repro outside of Stack Exchange, so here it is...


Steps to reproduce:

  • Run the first snippet, check the logged values. On a 60 Hz monitor, they should be around 60 FPS everywhere.
  • Start scrolling the main page. The values may start changing a bit (though normally only min should).
  • Run the second snippet and scroll back to the first one. See how max goes crazy out with numbers like 5,000 or 10,000 FPS (I believe the rounded value is due to performance.now()'s min precision, thanks Spectre). Checking the rAF timestamp in these frames gives us a difference of 0: multiple callbacks did fire in a single frame).

debugger; // apparently the code would be ran in both iframes?
const store = [];
let min = Infinity;
let max = -Infinity;
let lastRaf;
let rafID;
// start after everything warmed up
setTimeout(() => rafID = requestAnimationFrame(measure), 500);
function measure(rafTime) {
  // testing observations from Comment 7
  // make sure we have only one rAF(measure) scheduled at a time
  if (checkbox.checked) {
    cancelAnimationFrame(rafID);
  }
  const now = performance.now();
  if (store.length) {
    const diff = +(1000 / (now - store[store.length-1]));
    max = Math.max(diff, max);
    min = Math.min(diff, min);
    if(diff>1000) {
      console.log("timestamp-diff", rafTime - lastRaf);
    }
  }
  lastRaf = rafTime;
  store.push(now);
  if (store.length > 10) {
    store.shift();
  }
  const diffs = store.map((t,i,a) => (a[i+1]||t)-t);
  const sum = diffs.reduce((s,t) => s+t, 0);
  const avg = sum / (diffs.length - 1);
  log.textContent = `average: ${(1000 / avg).toFixed(2)}FPS
maximum: ${max.toFixed(2)}FPS
minimum: ${min.toFixed(2)}FPS`;
  rafID = requestAnimationFrame(measure)
}
.as-console-wrapper { max-height: 110px !important; }
<label><input type=checkbox id=checkbox> Cancel previous animation frame callback</label>
<pre id=log></pre>

<h1>hello</h1>

0

TypeScript is accepted if you use the Babel compiler option in the snippet.

interface Problem {
  num1: number;
  num2: number;
}

interface SolvedProblem extends Problem {
  result: number;
}

function add(a: number, b: number) {
  return a + b;
}

function print(s: string) {
  console.log(s);
}

function solve(p: Problem): SolvedProblem {
  return {
    ...p,
    result: add(p.num1, p.num2)
  };
}

const solution: SolvedProblem  = solve({num1: 3, num2: 5});

const formatted: string = `The sum of ${solution.num1} and ${solution.num2} is ${solution.result}`;

print(formatted);

-1

Test of animated demonstration of SQL joins using HTML canvas.

// Mulling the practicality of improving this and rewriting my 
// answer here when this functionality becomes available...
// http://stackoverflow.com/questions/13997365/sql-joins-as-venn-diagram/14011879#14011879

//Relies on code from http://dbp-consulting.com/scripts/canvasutilities.js for the arrows


function DoInnerJoin() {
            var predicate = function (a, b) { return a == b; };
            foo(4, "SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour", predicate, "inner")
        }

        function DoCrossJoin() {
            var predicate = function (a, b) { return true; };
            foo(16, "SELECT A.Colour, B.Colour FROM A CROSS JOIN B", predicate, "cross")
        }

        function DoLeftJoin() {
            var predicate = function (a, b) { return a == b; };
            foo(5, "SELECT A.Colour, B.Colour FROM A LEFT JOIN B ON A.Colour = B.Colour", predicate, "loj")
        }



        function foo(resultBlocks, caption, predicate, joinType) {
            if (joinType != "inner" && joinType != "cross" && joinType != "loj" && joinType != "roj") {
                alert("unexpected join type")
            }

            var isOuterJoin = (joinType == "loj" || joinType == "roj");
            var canvas, context;

            canvas = document.getElementById('imageView');
            context = canvas.getContext('2d');

            var lineWidth = 4;
            var blockWidth = 50;
            var blockHeight = 25;
            var table1blockLeft = 50;
            var table2blockLeft = 150;
            var blockHeight = 25;


            var canvasHeight = resultBlocks * blockHeight + 100;
            canvas.height = canvasHeight;
            var table1blockRight = table1blockLeft + blockWidth;

            context.lineWidth = lineWidth;
            context.strokeStyle = '#000000';
            context.fillStyle = '#000000';

            context.clearRect(0, 0, canvas.width, canvasHeight);
            context.font = "bold 10pt Arial";

            context.fillText(caption, 10, 10);



            var leftTableValues = ['#ff0000', '#75923C', '#75923C', '#8DB4E3'];
            var rightTableValues = ['#60497B', '#75923C', '#75923C', '#8DB4E3'];

            context.font = "bold 16pt Arial";
            context.fillText("A", 70, canvasHeight - 130);

            for (var i = leftTableValues.length; i > 0; i--) {
                drawBlock(table1blockLeft, leftTableValues[i - 1], i);
            }

            context.fillText("B", 170, canvasHeight - 130);
            for (var i = rightTableValues.length; i > 0; i--) {
                drawBlock(table2blockLeft, rightTableValues[i - 1], i);
            }

            var funcs = [];

            var resultBlocksDrawn = 0;
            for (var i = leftTableValues.length; i > 0; i--) {
                var thisLeftItemMatched = false;

                for (var j = rightTableValues.length; j > 0; j--) {

                    var matched = predicate(leftTableValues[i - 1], rightTableValues[j - 1]);

                    funcs[funcs.length] = function (i, j) {
                        return function () {
                            drawArrowBetweenBlocks(i, j);
                        };
                    } (i, j);



                    funcs[funcs.length] = function (matched) {
                        return function () {
                            context.font = "bold 16pt 'Arial Unicode MS'";
                            context.fillStyle = matched ? '#75923C' : '#ff0000';
                            context.fillText(matched ? "✔" : "✘", 120, canvasHeight - 130);
                        };
                    } (matched);


                    if (matched) {
                        thisLeftItemMatched = true;
                        resultBlocksDrawn++;

                        funcs[funcs.length] = function (i, j, resultBlocksDrawn) {
                            return function () {
                                drawBlock(300, leftTableValues[i - 1], resultBlocksDrawn);
                                drawBlock(350, rightTableValues[j - 1], resultBlocksDrawn);

                            };
                        } (i, j, resultBlocksDrawn);

                    }

                    if (isOuterJoin && !thisLeftItemMatched && j == 1) {
                        resultBlocksDrawn++;

                        funcs[funcs.length] = function () {
                            return function () {
                                context.font = "bold 10pt Arial";
                                context.fillStyle = '#000000'
                                context.fillText("No joining rows", 10, 50);
                            };
                        } ();

                        funcs[funcs.length] = function (i, j, resultBlocksDrawn) {
                            return function () {
                                drawBlock(300, leftTableValues[i - 1], resultBlocksDrawn);
                                drawBlock(350, '#ffffff', resultBlocksDrawn);

                            };
                        } (i, j, resultBlocksDrawn);


                        funcs[funcs.length] = function () {
                            return function () {
                                context.clearRect(10, 30, canvas.width, 25);
                            };
                        } ();

                    }

                    funcs[funcs.length] = function () {
                        return function () {
                            context.clearRect(100 + 2, 25, 50 - 4, canvasHeight - 25);
                        };
                    } ();

                }

            }


            console.log(funcs.length)
            ProcessQueueItem();


            function ProcessQueueItem() {

                var f = funcs.shift();
                console.log(f)
                f();

                if (funcs.length > 0) {
                    window.setTimeout(ProcessQueueItem, 250)
                }
            }

            function drawArrowBetweenBlocks(leftIndex, rightIndex) {
                var leftMid = canvasHeight + blockHeight / 2 - (leftIndex * blockHeight) - lineWidth;
                var rightMid = canvasHeight + blockHeight / 2 - (rightIndex * blockHeight) - lineWidth;
                drawArrow2(context, table1blockRight, leftMid, table2blockLeft, rightMid);
            }

            function drawArrow2(ctx, x1, y1, x2, y2, style, which, angle, d) {
                context.lineWidth = 2;
                context.fillStyle = '#000000';
                drawArrow(ctx, x1, y1, x2, y2, style, which, angle, d)
                context.lineWidth = lineWidth;
            }


            function drawBlock(blockLeft, fillStyle, blocksRemaining) {
                blockTop = canvasHeight - (blocksRemaining * blockHeight) - lineWidth;
                context.strokeRect(blockLeft, blockTop, blockWidth, blockHeight);
                context.fillStyle = fillStyle;
                context.fillRect(blockLeft + lineWidth / 2, blockTop + lineWidth / 2, blockWidth - lineWidth, blockHeight - lineWidth);
                context.fillStyle = '#000000';
            }



        }
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://dbp-consulting.com/scripts/canvasutilities.js"></script>
    <style type="text/css"><!--
#container { position: relative; }
#imageTemp { position: absolute; top: 1px; left: 1px; }
--></style>
</head>
<body>
  
    <div style="padding-bottom: 50px">
       <button onclick="DoCrossJoin()">
        Cross Join</button>
    <button onclick="DoInnerJoin()">
        Inner Join</button>
    <button onclick="DoLeftJoin()">
        Left Join</button></div>  
    <div>
        <canvas id="imageView" width="600" height="175"></canvas>
    </div>


    
</body>
</html>

1
  • Wait, was the hide feature included yesterday? (err, never mind)
    – gunr2171
    Sep 8, 2014 at 17:09
-1

Purdy Colours with D3

Verdict on the Snippet editor: Mostly great, but it has the same annoying feature as JSFiddle, with regards to the auto-indenting feature over-riding the correct indentation when using multi-line function chains.

E.g., when I type the following:

var td = tr.selectAll("td")
           .data(function(d,i){ return d3.range(0,255); });

As soon as I type a {, the second line gets pushed flush-left. I fix it, and then get to the }, and it happens again. Urgh.

var tb = d3.select("body").append("table");

var tr = tb.selectAll("tr")
           .data(d3.range(0,255) );

tr.enter().append("tr");

var td = tr.selectAll("td")
           .data(function(d,i){ return d3.range(0,255); });

td.enter().append("td");

td.style("background-color", function(d,i,j){ return d3.rgb(127, i, j); });
table, tr { 
  border:none; 
  border-collapse:collapse; 
  padding:0; 
  margin:0; 
}
td {
  padding:1px; 
  border:none; 
  margin: 0;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

3
  • Unfortunately the editor is not advanced enough to understand this aspect. I might be able to make the auto-indenting a checkbox though.
    – Haney StaffMod
    Sep 9, 2014 at 15:48
  • That would work. As I said on the main feedback post, there isn't exactly an agreed-upon standard for what indenting should be, but it is rather annoying when I indent things "just so" for readability, and then the algorithm pushes my code all around.
    – AmeliaBR
    Sep 9, 2014 at 16:37
  • I turned off the feature that automatically re-indents the current line based on characters. We'll see how people enjoy it (I imagine it'll be fine). It'll go live next build.
    – Haney StaffMod
    Sep 10, 2014 at 15:21
-1

This is a test about the code snippet function for this question on WPSE, there have not htis nice feature: https://wordpress.stackexchange.com/questions/194271/how-to-disabled-a-button-when-press-three-times/194272

jQuery( document ).ready( function( $ ) {

    var counter = 1,
        element = 'input.edit';

    $( element ).click( function(e) {
        counter ++;
        // for control debugging in console
        console.log( counter );
        if ( counter > 3 ) {
            $( element ).attr( 'disabled', true );
        }
    } )

} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input" class="edit" value="Click here">

-1

This is somewhat odd.

We cannot test media queries at the default box, like we'd do with jsFiddle frames.

Currently, we must click at Full Page to be able to resize and test different media queries.

img {
  width: 100px;
  height: 100px;
  background-color: red;
}

@media (max-width: 500px) {
  img {
    background-color: green;
  }
}
<img />

-1

var username = window.prompt("What is your username?");
var password = window.prompt("What is your password?");
if (!password){
    alert("You haven't entered the password yet.")
}else if (!username){
    alert("You haven't entered the username yet.")
}else{
    //TODO: save username and password to my website
    alert("Thanks!");
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .