Recent Entries 10
- pattern tip 105d agoCreating standalone HTML design mockups for layout comparisonWhen redesigning a page layout (e.g., converting a long vertical scroll into a workspace), teams need to compare multiple layout options side by side. Building these as React components is slow and couples mockups to the codebase. Need a fast way to create visual previews that stakeholders can open in any browser.
- pattern minor 112d agoJavaScript calculator with two inputs and four operationsi build a calc & want to a review that what i did wrong & what is right method to do. ` var inputIdFirst = "valueOfX",inputIdSecond = "valueOfY",outputId = "resultHere"; var getInputs = function(id) { return parseInt(document.getElementById(id).value); } var showOutput = function(outputValue, outputIdAsArg) { //if no argument is given then by default "outputId" taken document.getElementById(outputId).innerHTML = outputValue; } var manuplateAs = function(operationName, valueOfX, valueOfY) { if(operationName == 'add') return valueOfX + valueOfY; else if(operationName == 'sub') return valueOfX - valueOfY; else if(operationName == 'mul') return valueOfX * valueOfY; else if(operationName == 'div') return valueOfX / valueOfY; //can add as many as you wish } var operation = function(operationName){ x = getInputs(inputIdFirst); y = getInputs(inputIdSecond); output = manuplateAs(operationName, x, y); showOutput(output); console.log(x + " " + operationName + " " + y + " = " + output) //see console to understand this more console.log(this) }; Enter first number Enter second number Add Sub Mult Divi `
- snippet minor 112d agoClass to create HTML heading tags in ReactI have a class which is part of my page layout. It is creating header tag elements (`h1` - `h5`). Could someone tell me how I could improve it (I know it should be improved, but don't know how)? I have problem with rewriting almost the same code in switch cases. Would rather to create some kind of `` code, but couldn't. ``` import React, {Component} from 'react'; import PropTypes from 'prop-types'; export class TypographyHeader extends Component { createHeader() { let txt = this.props.text; let spaceIndex = txt.indexOf(' '); let p2 = txt.substr(spaceIndex); txt = {txt.substr(0, spaceIndex)} ; switch(this.props.headerType) { case 1: return {txt} {p2}; case 2: return {txt} {p2}; case 3: return {txt} {p2}; case 4: return {txt} {p2}; case 5: return {txt} {p2}; } return {txt} {p2}; } render() { return ( {this.createHeader()} ); } } TypographyHeader.propTypes = { headerType: PropTypes.oneOf([1, 2, 3, 4, 5]).isRequired, text: PropTypes.string.isRequired, }; ```
- pattern minor 112d agoDrawing a circle with text in it using CSSI'm trying to draw a circle and put text in the circle. It'll be part of a UI I'm working on. I have it working and it looks the way I want, but I think there must be a better way to do it. Mainly, I don't like all the hard coded numbers and lining up everything by hand. What I'd love is a version that could easily scale to any size without having to change a lot of the `top` and `left` properties of all the text. Any ideas on how to improve this? Fiddle `div.arcs { border: 50px solid red; display: inline-block; min-width: 14em; min-height: 14em; max-height: 14em; max-width: 14em; border-radius: 50%; border-top-color: rgb(109, 176, 65); border-bottom-color: rgb(167, 167, 167); border-left-color: rgb(255, 199, 45); border-right-color: rgb(104, 162, 219); box-shadow: 0 0 20px 5px #a0a0a0; } div.arcs > div { font-family: Calibri; font-size: 20pt; text-align: center; text-shadow: 1px 1px 3px #000000; color: #e0e0e0; position: relative; width: 8.45em; height: 1.5em; line-height: 1.35em; } div.arcs > div:hover { text-decoration: underline; cursor: pointer; } div.arcs > div.top { top: -1.55em; } div.arcs > div.left { transform: rotate(270deg); transform-origin: right top 0; left: -10em; top: -1.5em; } div.arcs > div.right { transform: rotate(90deg); transform-origin: left top 0; left: 10em; top: -3.1em; } div.arcs > div.bottom { top: 3.7em }` ` Text 1 Text 4 Text 2 Text 3 `
- pattern minor 112d agoSelect box to highlight choice deviationI have a select box that in default state looks as default (white, etc) but when I select a different value, I want the entire table row to highlight in yellow. I did this, but I want to make it better and more concise and more efficient. Can you help? Also I will have several such boxes, not just one. Feel free to change/add/remove identifiers, I am looking for a better solution overall. `$(document).ready(function() { $("#closedRow").on('change', function() { if ($("#closedRow").val() != 0) $("#trRow").css('background-color', 'yellow'); else $("#trRow").css('background-color', 'white'); }) $("#serviceRow").on('change', function() { if ($("#serviceRow").val() != 0) $("#trRow2").css('background-color', 'yellow'); else $("#trRow2").css('background-color', 'white'); }) })` ` Closed: Show All Hide Closed Service: Show All Hide Service Another Service `
- pattern minor 112d agoSimple Javascript AccordionI have put together a simple Javascript accordion, though the Javascript code I think could possibly be slimmed down. I would welcome any feedback anyone has on what I have done, and any advice to improve. HTML ``` Accordion 1 Cras malesuada ultrices augue molestie risus. Accordion 2 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae at placeat nesciunt nostrum accusamus debitis fuga similique quisquam, rerum temporibus, quod asperiores nulla, eveniet libero earum eaque harum inventore minima ipsum saepe omnis. Officia, est, maiores. Reprehenderit odio perspiciatis voluptates commodi ex at praesentium laborum deleniti libero, architecto sit optio repellat est molestiae beatae, magnam qui voluptatibus. Ducimus mollitia dignissimos minus sapiente quidem, animi adipisci laboriosam aliquam asperiores facere. Repellat recusandae doloribus incidunt voluptatibus quibusdam rem delectus inventore nisi, laudantium. Doloribus eum vero, consequuntur nisi enim quam non odio dignissimos praesentium nostrum magnam consequatur totam reprehenderit quaerat. Saepe, blanditiis fugit? Accordion 3 Vivamus facilisisnibh scelerisque laoreet. ``` SCSS ``` div.accordion { .accordion-content { max-height: 0px; overflow: hidden; transition: max-height 400ms; &.active { overflow: auto; } } } ``` JavaScript ``` document.addEventListener('DOMContentLoaded', function() { function toggle(){ if (this.nextElementSibling.classList.contains('active')) { this.nextElementSibling.classList.remove('active'); this.nextElementSibling.removeAttribute('style'); this.classList.remove('active'); } else { var elementHeight = this.nextElementSibling.scrollHeight; this.nextElementSibling.classList.add('active'); this.nextElementSibling.style.maxHeight = elementHeight + 'px'; this.classList.add('active'); } } var accordion = document.querySelector('.js div.acco
- pattern minor 112d agoSimon Game in JavaScriptI've made a JavaScript, HTML and CSS version of the memory game 'Simon' from the 70s. The design of the board is not too impressive (I wanted to focus first on the JavaScript part) but I also appreciate feedback on it of course. If you want to see the game already in action, it's available here. `var computerMovements = []; var answers = []; var rounds = 0; //strict mode allows one mistake per round. false if 'relaxed' mode var strict = true; //in strict mode, there is no last chance var lastChance = false; var addColor = function(arr) { var colorsArray = ["green", "red", "yellow", "blue"]; return arr.push(colorsArray[Math.floor(Math.random() * colorsArray.length)]); }; var flashLights = function(arr) { var i = 0; var interval = setInterval(function() { $("#" + arr[i]).fadeTo("slow", 0).fadeTo("slow", 1); $("#sound-" + arr[i])[0].play(); i++; if (i >= arr.length) { clearInterval(interval); } }, 1500); }; var resetAnswers = function() { answers = []; }; var updateRounds = function() { rounds++; $("#show-rounds").html(rounds); }; var resetGame = function() { rounds = 0; computerMovements = []; if (strict === false) { lastChance = true; } resetAnswers(); }; var playerTurn = function() { //during the game we don't want the player to switch between strict and relaxed $("#mode").click(function() { return false; }); //winning condition if (rounds === 20) { alert("You, you, you're good you!"); resetGame(); } updateRounds(); addColor(computerMovements); flashLights(computerMovements); $(".button").off("click").on("click", function() { $("#sound-" + $(this).attr("id"))[0].play(); answers.push($(this).attr("id")); for (var i = 0; i `#container { background-color: gray; width: 160px; height: 160px; margin: 0 auto; text-align: center; text-align: justify; } #green { background-color: green; width: 70px; height: 70px; float: left; } #red {
- pattern minor 112d agoGolang function to clean a string of scriptsI am trying to make an efficient algorithm for removing script tags from an HTML string. Can someone point out any flaws in this? This seems to be the best I could think of. ``` func removeScripts(s string) string { startingScriptTag := "" var script string for { startingScriptTagIndex := strings.Index(s, startingScriptTag) endingScriptTagIndex := strings.Index(s, endingScriptTag) if startingScriptTagIndex > -1 && endingScriptTagIndex > -1 { script = s[startingScriptTagIndex:endingScriptTagIndex + len(endingScriptTag)] s = strings.Replace(s, script, "", 1) continue } break } return s } ```
- pattern minor 112d agoKeeping a search history in localStorage, with a length limitI'm having a problem figuring out how I can make this particular part of my code DRY. Currently, the code is repeating itself but with minor changes in each case of a switch. SearchParam is a string that the user has searched for in the application that this code is from. The function creates a new li element with searchParam as the text. This value is then added to localStorage as 'search1'. Dependent on how many li elements there are already, the function uses a switch to add the new li element to the beginning of the list. If there are already 3 items, then the last item in the list will be deleted and removed. ``` function searchHistory(searchParam) { var liElements = $('#history').children(); var recentSearch = liElements.first(); var newItem = ` ${searchParam} `; switch($('#history').children().length) { case 0: $('#history').append(newItem); localStorage.setItem('search1', searchParam); break; case 1: var secondSearch = liElements.children()[1].innerHTML; recentSearch.before(newItem); localStorage.setItem('search1', searchParam); localStorage.setItem('search2', secondSearch); break; case 2: var secondSearch = liElements.children()[1].innerHTML; var thirdSearch = liElements.children()[3].innerHTML; recentSearch.before(newItem); localStorage.setItem('search1', searchParam); localStorage.setItem('search2', secondSearch); localStorage.setItem('search3', thirdSearch); break; default: var oldSearch = liElements.last(); var secondSearch = liElements.children()[1].innerHTML; var thirdSearch = liElements.children()[3].innerHTML; localStorage.setItem('search1', searchParam); localStorage.setItem('search2', secondSearch); localStorage.setItem('search3', thirdSearch); recentSearch.before(newItem); oldSearch.remove(); }
- debug minor 112d agoFixed table header with scrollable body and aligning columnsHere is my solution for a fixed table header with scrollable body and aligning columns. The requirements I wanted to achieve were: - Fix `` while `` can scroll while the all the `` and `` cells of one column all have the same width - No fixed `width` - Pure `HTML`, `CSS`, `JS` - Bonus points for pure `CSS` solution What could still be improved: - Make the scroll bar as longer so there is no free area in the top right - Improve the `Javascript`, I'm sure it can be rewrote to be more efficient - Clean the code, especially the `Javascript` - Pure CSS solution, if possible I would also like to have general advice on my coding style, good or bad practices and maybe an evaluation of how efficient this code is. How good would it perform if the matrix size grows? Right now, I'm just happy that my code works in my case. :) You can find the matrix that needs to be tweaked here: JsFiddle The table in this example is from a match plan for last year for my sports team. `// jshint esversion: 6 // jshint browser: true // jshint devel: true const thElements = document.getElementsByTagName("th"); const tdElements = document.getElementsByTagName("td"); let width = []; let tempResult = 0; // calculate needed width for (let i = 0; i tdElements[i].offsetWidth) { // get inner width because thats what we will set tempResult = window.getComputedStyle(thElements[i], null) .getPropertyValue("width"); width[i] = `${tempResult.toString()}`; } else { // get inner width because thats what we will set tempResult = window.getComputedStyle(tdElements[i], null) .getPropertyValue("width"); width[i] = `${tempResult.toString()}`; } } // set column width for (let i = 0; i `/*container */ #club_plan { clear: both; overflow-x: auto; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%) } thead tr { position: relative; } tbody { display: block; max-height: 15