Adding and removing borders dynamically to WebGL canvases - javascript

I have the following code for generating an html canvas:
<canvas id="glCanvas" class="canvases" width="20" height="20"></canvas>
and to set the colour I have the following:
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
Is there an easy way to add and remove borders dynamically at run time? That is, when a specific if-statement condition is met, a red border is drawn around the canvas, and when this is no longer met the border is removed. Can this be done using either CSS/Javascript/WebGL?
Thank you

Your question has nothing to do with WebGL or canvases in particular. You can set a border on any element with something like
someElement.style.border = "10px solid red";
And remove the border with
someElement.style.border = "none";
For canvas I'd suggest you wrap the canvas in a div like this
<div id="border"><canvas id="glCanvas"></canvas></div>
Then look up the div
borderDiv = document.querySelector("#border");
And based on whatever conditions use code like that at the top;
const borderDiv = document.querySelector("#border");
const showButton = document.querySelector("#show");
const hideButton = document.querySelector("#hide");
showButton.addEventListener('click', function() {
borderDiv.style.border = "10px solid red";
});
hideButton.addEventListener('click', function() {
borderDiv.style.border = "none";
});
// draw something in canvas.
const gl = document.querySelector("#glCanvas").getContext("webgl");
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);
#border { display: inline-block; }
#glCanvas { width: 100%; height: 100%; display: block; }
<div id="border"><canvas id="glCanvas"></canvas></div>
<div>
<button id="show">show border</button>
<button id="hide">hide border</button>
</div>
You can also do it be adding and removing styles
someElement.className = "styleWithBorder";
someElement.className = "styleWithoutBorder";
You can apply multiple classes by separating them with spaces
someElement.className = "style1 style2";
const borderDiv = document.querySelector("#border");
const showButton = document.querySelector("#show");
const hideButton = document.querySelector("#hide");
showButton.addEventListener('click', function() {
borderDiv.className = "styleWithBorder";
});
hideButton.addEventListener('click', function() {
borderDiv.className = "";
});
// draw something in canvas.
const gl = document.querySelector("#glCanvas").getContext("webgl");
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);
/* these 2 lines make the border go inside the element
instead of outside IF the element has a defined width and height */
html { box-sizing: border-box; height: 100%; }
*, *:before, *:after { box-sizing: inherit; }
/* this setting removes the default 5px margin on the body
and makes the body fill the window so our div will match */
body { margin: 0; height: 100%; }
/* this line makes our border fill the body. We need to set
the size so the border will go inside */
#border { width: 100%; height: 100%; }
/* this line makes the canvas fill the div it's inside
and display:block makes it not add whitespace at the end */
#glCanvas { width: 100%; height: 100%; display: block; }
/* here's our border */
.styleWithBorder { border: 10px solid yellow; }
/* make the ui show up over the rest */
#ui { position: absolute; left: 1em; top: 1em; }
<div id="border"><canvas id="glCanvas"></canvas></div>
<div id="ui">
<button id="show">show border</button>
<button id="hide">hide border</button>
</div>

Related

Change word color in input or textarea

For a chat app, I need to change the color of words starting with a special character, #word inside an input tag, i.e:
Hello #John how are you?
the part #John should change color inside the input, i.e:
Hello #John how are you?
It works after it's posted, but that's obviously another code. I want it to highlight words (#mention) by changing its color right in the input or textarea Element.
Color specific text inside a textarea-alike element
One 5y old idea (Highlight syntax in contenteditable) would be to:
let the user type into a contenteditable DIV with transparent color but visible caret, then get and modify the content on the fly as-you-ype to an underlying DIV, used as a markup highlighter.
Basically:
On "input" event get the editable innerHTML, do some String.prototype.replace() with a regular expression that matches #mentions on the contenteditable value and replace i.e: #John with <span class="mention">#John</span>
Write the result as HTML to the underlying (highlighter) DIV element.
This way you're not replacing and creating any child SPAN elements in the area where the user is typing, but actually on the underlying one.
const colorMention = (elText, elPre) => {
elPre.innerHTML = elText.innerHTML.replace(/(?<=^| )#\p{L}+/gu, "<span class='mention'>$&</span>");
};
const scrollMirror = (elText, elPre) => {
elPre.scrollTo(elText.scrollLeft, elText.scrollTop);
};
const handleKey = (ev, elText, elPre) => {
if (ev.key === "Enter" && !ev.shiftKey) {
// prevent Enter key behavior (new-line)
ev.preventDefault();
// Check message to send...
const message = elText.innerHTML;
if (!message.trim()) {
return; // Nothing to submit. Message is empty
}
// YOUR SUBMIT LOGIC GOES HERE:
console.log(message);
// Clear fields:
elText.innerHTML = "";
elPre.innerHTML = "";
} else {
// Any other key: (scroll areas is necessary)
scrollMirror(elText, elPre);
}
};
document.querySelectorAll(".message").forEach(el => {
const elText = el.querySelector(".text");
const elPre = el.querySelector(".pre");
elText.addEventListener("scroll", () => scrollMirror(elText, elPre));
elText.addEventListener("keyup", () => scrollMirror(elText, elPre));
elText.addEventListener("input", () => colorMention(elText, elPre));
elText.addEventListener("keydown", (ev) => handleKey(ev, elText, elPre));
// Init:
colorMention(elText, elPre);
scrollMirror(elText, elPre);
});
* {
margin: 0;
box-sizing: border-box;
}
body {
font: 16px/1.3 sans-serif;
}
.message {
display: block;
border: 1px solid #888;
position: relative;
width: 100%;
border: 1px solid #ccc;
}
.message .pre,
.message .text {
border: 0;
overflow: scroll;
overflow-x: hidden;
font: inherit;
padding: 10px;
height: 5rem;
resize: none;
width: 100%;
white-space: break-spaces;
word-wrap: break-word;
}
/* The overlay contenteditable with transparent text but visible caret */
.message .text {
position: relative;
background: transparent;
outline: none;
/* transparent color */
color: transparent;
/* but visible caret */
caret-color: black;
}
/* The underlaying element with colors */
.message .pre {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* Prevent text selections */
user-select: none;
}
.mention {
color: fuchsia;
}
<div class="message">
<div class="pre"></div>
<div class="text" contenteditable spellcheck="false">Hi #Roko, how are you today?</div>
</div>
<br>
Chat tips:<br> Use <code>#username</code> to mention a user.<br> Use <kbd>Enter</kbd> to send.<br> Use <kbd>Shift</kbd>+<kbd>Enter</kbd> to go to a new line.<br>
Regarding the regular expression for matching mentions:
/(?<=^| )#\p{L}+/gu
here's a Regex101.com example with description, and a related answer.

How can I get and set style properties of an object that come from a class?

I have a simple animation function that simulates a button being pushed, by varying the width:
function bPress(b) {
var w = (parseFloat(b.style.width)*0.96);
if (b.style.width.substr(-1)=="%") {
var s ="%";
}
else {
var s = "em";
}
b.style.width = w +s;
b.onmouseup = function () {
w = (parseFloat(b.style.width)/0.96);
b.style.width = w+s;
// etc.
}
This was working well until I started cleaning up my code and changed inline CSS style declarations to classes. I previously had, for example:
<div style= 'height: 1.5em; width: 100%; margin: 0 auto; margin-top: 0.2em; font: inherit; font-weight:bold' onclick='checkSave("continue")' onmousedown='bPress(this)'>Continue</div>
I moved the CSS parts to a new class:
.response_button {
height: 1.5em;
width: 100%;
margin: 0 auto;
margin-top: 0.2em;
font: inherit;
font-weight:bold
}
... avoiding repetition and of course simplifying the div tags.
But the animations stopped working. After some experimenting, I eventually came up with a temporary solution by moving the width back into an inline style declaration. But this seems wrong.
So 2 questions:
Why does this.style.width not work if the width is declared inside a class?
Is there a way to get and set a div's properties if they are declared inside a class?
Edit: For completeness, using nick zoum's answer, here is the modified bPress function:
function bPress(b) {
var w_px = window.getComputedStyle(b).width;
var w_int = (parseInt(w_px));
b.style.width = Math.round(w_int * 0.96) + "px";
b.onmouseup = function () {
b.style.width = w_px;
}
}
You can use getComputedStyle to get all of the calculated style properties of an element.
var dom = document.querySelector("#foo");
console.log(getComputedStyle(dom).backgroundColor);
#foo {
background-color: red;
width: 10px;
height: 10px;
}
<div id="foo"></div>

Making a dragbar to resize divs inside CSS grids

I have 2 boxes and a vertical div line in one unique container div (code and fiddle below).
I'm using CSS grids to position my elements inside the container
What I'd like to accomplish is to use the vertical line to resize horizontally the two boxes based on the position of the vertical line.
I apologize if the question is noobish, I am new to web development, only used Python before, already tried to google and stackoverflow search but all solutions seem overly complicated and generally require additional libraries, I was looking for something simpler and JS only.
HTML:
<div class="wrapper">
<div class="box a">A</div>
<div class="handler"></div>
<div class="box b">B</div>
</div>
CSS:
body {
margin: 40px;
}
.wrapper {
display: grid;
grid-template-columns: 200px 8px 200px;
grid-gap: 10px;
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
resize: both;
}
.handler{
width: 3px;
height: 100%;
padding: 0px 0;
top: 0;
background: red;
draggable: true;
}
https://jsfiddle.net/gv8Lwckh/6/
What you intend to do can be done using CSS flexbox—there is no need to use CSS grid. The bad news is that HTML + CSS is not so smart that declaring resize and draggable will make the layout flexible and adjustable by user interaction. For that, you will have to use JS. The good news is that this is actually not too complicated.
Here is a quick screen grab of output the code below:
However, for you to understand the code I will post below, you will have to familiarize yourself with:
Event binding using .addEventListener. In this case, we will use a combination of mousedown, mouseup and mousemove to determine whether the user is in the middle of dragging the element
CSS flexbox layout
Description of the solution
Initial layout using CSS
Firstly, you will want to layout your boxes using CSS flexbox. We simply declare display: flex on the parent, and then use flex: 1 1 auto (which translates to "let the element grow, let the element shrink, and have equal widths). This layout is only valid at the initial rendering of the page:
.wrapper {
/* Use flexbox */
display: flex;
}
.box {
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
flex: 1 1 auto;
}
Listen to drag interaction
You want to listen to mouse events that might have originated from your .handler element, and you want a global flag that remembers whether the user is dragging or not:
var handler = document.querySelector('.handler');
var isHandlerDragging = false;
Then you can use the following logic to check if the user is dragging or not:
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
// Set boxA width properly
// [...more logic here...]
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
Computing the width of box A
All you are left with now is to compute the width of box A (to be inserted in the [...more logic here...] placeholder in the code above), so that it matches that of the movement of the mouse. Flexbox will ensure that box B will fill up the remaining space:
// Get offset
var containerOffsetLeft = wrapper.offsetLeft;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientX - containerOffsetLeft;
// Resize box A
// * 8px is the left/right spacing between .handler and its inner pseudo-element
// * Set flex-grow to 0 to prevent it from growing
boxA.style.width = (pointerRelativeXpos - 8) + 'px';
boxA.style.flexGrow = 0;
Working example
var handler = document.querySelector('.handler');
var wrapper = handler.closest('.wrapper');
var boxA = wrapper.querySelector('.box');
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
// Get offset
var containerOffsetLeft = wrapper.offsetLeft;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientX - containerOffsetLeft;
// Arbitrary minimum width set on box A, otherwise its inner content will collapse to width of 0
var boxAminWidth = 60;
// Resize box A
// * 8px is the left/right spacing between .handler and its inner pseudo-element
// * Set flex-grow to 0 to prevent it from growing
boxA.style.width = (Math.max(boxAminWidth, pointerRelativeXpos - 8)) + 'px';
boxA.style.flexGrow = 0;
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
body {
margin: 40px;
}
.wrapper {
background-color: #fff;
color: #444;
/* Use flexbox */
display: flex;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
flex: 1 1 auto;
}
.handler {
width: 20px;
padding: 0;
cursor: ew-resize;
flex: 0 0 auto;
}
.handler::before {
content: '';
display: block;
width: 4px;
height: 100%;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="box">A</div>
<div class="handler"></div>
<div class="box">B</div>
</div>
Here's an example of the drag event handling, but using CSS Grids
The trick is to set the grid-template-columns (or rows) on the grid container rather than than the size of the grid items
let isLeftDragging = false;
let isRightDragging = false;
function ResetColumnSizes() {
// when page resizes return to default col sizes
let page = document.getElementById("pageFrame");
page.style.gridTemplateColumns = "2fr 6px 6fr 6px 2fr";
}
function SetCursor(cursor) {
let page = document.getElementById("page");
page.style.cursor = cursor;
}
function StartLeftDrag() {
// console.log("mouse down");
isLeftDragging = true;
SetCursor("ew-resize");
}
function StartRightDrag() {
// console.log("mouse down");
isRightDragging = true;
SetCursor("ew-resize");
}
function EndDrag() {
// console.log("mouse up");
isLeftDragging = false;
isRightDragging = false;
SetCursor("auto");
}
function OnDrag(event) {
if (isLeftDragging || isRightDragging) {
// console.log("Dragging");
//console.log(event);
let page = document.getElementById("page");
let leftcol = document.getElementById("leftcol");
let rightcol = document.getElementById("rightcol");
let leftColWidth = isLeftDragging ? event.clientX : leftcol.clientWidth;
let rightColWidth = isRightDragging ? page.clientWidth - event.clientX : rightcol.clientWidth;
let dragbarWidth = 6;
let cols = [
leftColWidth,
dragbarWidth,
page.clientWidth - (2 * dragbarWidth) - leftColWidth - rightColWidth,
dragbarWidth,
rightColWidth
];
let newColDefn = cols.map(c => c.toString() + "px").join(" ");
// console.log(newColDefn);
page.style.gridTemplateColumns = newColDefn;
event.preventDefault()
}
}
#page {
height: 100%;
background-color: pink;
display: grid;
grid-template-areas: 'header header header header header' 'leftcol leftdragbar tabs tabs tabs' 'leftcol leftdragbar tabpages rightdragbar rightcol' 'leftcol leftdragbar footer footer footer';
grid-template-rows: min-content 1fr 9fr 1fr;
grid-template-columns: 2fr 6px 6fr 6px 2fr;
}
/*****************************/
#header {
background-color: lightblue;
overflow: auto;
grid-area: header;
}
#leftcol {
background-color: #aaaaaa;
overflow: auto;
grid-area: leftcol;
}
#leftdragbar {
background-color: black;
grid-area: leftdragbar;
cursor: ew-resize;
}
#tabs {
background-color: #cccccc;
overflow: auto;
grid-area: tabs;
}
#tabpages {
background-color: #888888;
overflow: auto;
grid-area: tabpages;
}
#rightdragbar {
background-color: black;
grid-area: rightdragbar;
cursor: ew-resize;
}
#rightcol {
background-color: #aaaaaa;
overflow: auto;
grid-area: rightcol;
}
#footer {
background-color: lightblue;
overflow: auto;
grid-area: footer;
}
<body onresize="ResetColumnSizes()">
<div id="page" onmouseup="EndDrag()" onmousemove="OnDrag(event)">
<div id="header">
Header
</div>
<div id="leftcol">
Left Col
</div>
<div id="leftdragbar" onmousedown="StartLeftDrag()"></div>
<div id="tabs">
Tabs
</div>
<div id="tabpages">
Tab Pages
</div>
<div id="rightdragbar" onmousedown="StartRightDrag()"></div>
<div id="rightcol">
Rightcol
</div>
<div id="footer">
Footer
</div>
</div>
</body>
https://codepen.io/lukerazor/pen/GVBMZK
I changed, so you can add more Horizontal and Vertical slider.
test1.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="test1.css">
<script src= "test1.js" > </script>
</head>
<body>
<div id="page" onmouseup="EndDrag()" onmousemove="OnDrag(event)">
<div id="header">
Header asdlkj flkdfj sdflkksdjf sd;flsdjf sd;flkjsd;fljsd;flsdj;fjsd f;sdlfj;sdlfj
</div>
<div id="leftcol">
Left Col
</div>
<div id="leftdragbar" onmousedown="StartHDrag(1)"></div>
<div id="tabs">
Tabs
</div>
<div id="topdragbar" onmousedown="StartVDrag(2)"></div>
<div id="tabpages">
Tab Pages
</div>
<div id="rightdragbar" onmousedown="StartHDrag(3)"></div>
<div id="rightcol">
Rightcol
</div>
<div id="botdragbar" onmousedown="StartVDrag(4)"></div>
<div id="footer">
Footer
</div>
</div>
<div id= 'status'></div>
</body>
</html>
test1.css
body {
}
#page {
height: 100vh;
background-color: pink;
display: grid;
grid-template-areas:
'header header header header header'
'leftcol leftdragbar tabs tabs tabs'
'leftcol leftdragbar topdragbar topdragbar topdragbar'
'leftcol leftdragbar tabpages rightdragbar rightcol'
'botdragbar botdragbar botdragbar botdragbar botdragbar'
'footer footer footer footer footer';
grid-template-rows: min-content 1fr 6px 9fr 6px 1fr;
grid-template-columns: 2fr 6px 6fr 6px 2fr;
}
/*****************************/
#header {
background-color: lightblue;
overflow: auto;
grid-area: header;
}
#leftcol {
background-color: #aaaaaa;
overflow: auto;
grid-area: leftcol;
}
#leftdragbar {
background-color: black;
grid-area: leftdragbar;
cursor: ew-resize;
}
#topdragbar {
background-color: black;
grid-area: topdragbar;
cursor: ns-resize;
}
#botdragbar {
background-color: black;
grid-area: botdragbar;
cursor: ns-resize;
}
#tabs {
background-color: #cccccc;
overflow: auto;
grid-area: tabs;
}
#tabpages {
background-color: #888888;
overflow: auto;
grid-area: tabpages;
}
#rightdragbar {
background-color: black;
grid-area: rightdragbar;
cursor: ew-resize;
}
#rightcol {
background-color: #aaaaaa;
overflow: auto;
grid-area: rightcol;
}
#footer {
background-color: lightblue;
overflow: auto;
grid-area: footer;
}
test1.js
let isHDragging = false;
let isVDragging = false;
let cols = ['2fr','6px','6fr','6px','2fr']; //grid-template-columns: 2fr 6px 6fr 6px 2fr;
let colns = ['leftcol','','tabpages','','rightcol'];
let Tcols = [];
let rows = ['min-content','1fr','6px','9fr','6px','1fr']; //grid-template-rows: min-content 1fr 6px 9fr 1fr
let rowns = ['header','tabs','','tabpages','','footer'];
let Trows = []
let CLfactor ;
let CRfactor ;
let gWcol = -1;
let gWrow = -1;
function StartHDrag(pWcol) {
isHDragging = true;
SetCursor("ew-resize");
CLfactor = parseFloat(cols[pWcol-1]) / document.getElementById(colns[pWcol-1]).clientWidth;
CRfactor = parseFloat(cols[pWcol+1]) / document.getElementById(colns[pWcol+1]).clientWidth;
Tcols = cols.map(parseFloat);
gWcol = pWcol;
}
function StartVDrag(pRow) {
isVDragging = true;
SetCursor("ns-resize");
CLfactor = parseFloat(rows[pRow-1]) / document.getElementById(rowns[pRow-1]).clientHeight;
CRfactor = parseFloat(rows[pRow+1]) / document.getElementById(rowns[pRow+1]).clientHeight;
Trows = rows.map(parseFloat);
gWrow = pRow;
}
function SetCursor(cursor) {
let page = document.getElementById("page");
page.style.cursor = cursor;
}
function EndDrag() {
isHDragging = false;
isVDragging = false;
SetCursor("auto");
}
function OnDrag(event) {
if(isHDragging) {
Tcols[gWcol-1] += (CLfactor * event.movementX);
Tcols[gWcol+1] -= (CLfactor * event.movementX);
cols[gWcol-1] = Math.max(Tcols[gWcol-1],0.01) + "fr";
cols[gWcol+1] = Math.max(Tcols[gWcol+1],0.01) + "fr";
let newColDefn = cols.join(" ");
page.style.gridTemplateColumns = newColDefn;
} else if (isVDragging) {
Trows[gWrow-1] += (CLfactor * event.movementY);
Trows[gWrow+1] -= (CLfactor * event.movementY);
rows[gWrow-1] = Math.max(Trows[gWrow-1],0.01) + "fr";
rows[gWrow+1] = Math.max(Trows[gWrow+1],0.01) + "fr";
let newRowDefn = rows.join(" ");
page.style.gridTemplateRows = newRowDefn;
document.getElementById("footer").innerHTML = newRowDefn;
}
event.preventDefault()
}
To actually match the question! Making a dragbar to resize divs inside CSS grids.
Here is a possible way, the original OP layout is kept, as well as the CSS, using Grids.
The goal is to capture the original state of the Grid Template Columns, and convert it to floats.
The browser always compute in pixels, and the sum of those columns + the gap, represent the total width of the container element. That sum must always be the same, or the elements will jump!
NB: Calls to .getComputedStyle() are not very efficient, optimisation is likely possible here!
Notice, doing this way using grids and screenX avoid the common jumping bug on mouse down.
Comments are added, this will allow to apply the logic with any number of columns, or rows, good luck.
With the usage of pointer events, it does works from a touch device as well.
let target = document.querySelector("div") // Target container element
let md = false; // Will be true at mouse down
let xorigin; // Click origin X position
let gtcorigin = []; // Origin Grid Template Columns in pixels
const pointerdown = (e) => {
if (e.target.classList[0] === "handler"){ // Filter to target the wanted element
md = true; // Set mouse down
xorigin = e.screenX; // Store the origin X position
// Grid Template Columns, array of pixels as float
gtcorigin = window.getComputedStyle(target)["grid-template-columns"].split(" ").map((a) => +(a.slice(0, -2)));
document.body.style.cursor = "col-resize" // This makes things nice
document.body.style.userSelect = "none" // This makes things nice
}
}
const pointerup = (e) => {
md = false; // Reset bool at mouse up
document.body.style.cursor = "pointer"
document.body.style.userSelect = "unset"
}
const resizer = (e) => {
if (md){ // Mouse is down hover the handler element
let gtc = window.getComputedStyle(target)["grid-template-columns"].split(" ").map((a) => +(a.slice(0, -2))); // Grid Template Columns, array of pixels as float
let xdragdif = xorigin - e.screenX; // Move in pixels since the click
gtc[0] = gtcorigin[0] - xdragdif // First column, if negative, it will grow
gtc[2] = gtcorigin[2] + xdragdif // Third column
gtc = gtc.map((a) => a+"px") // Set back the values in string with "px"
document.querySelector("console").textContent = gtc.join(" ") // !!! This is only for the demo
target.style.gridTemplateColumns = gtc.join(" ") // Apply the new Grid Template Column as inline style.
}
}
// Attach all events on the largest container element. Here the body is used.
document.body.addEventListener("pointerdown", pointerdown, false)
document.body.addEventListener("pointerup", pointerup, false)
document.body.addEventListener("pointermove", resizer, false)
body {
margin: 40px;
overflow-x: hidden
}
.wrapper {
display: grid;
grid-template-columns: 200px 8px 200px;
grid-gap: 10px;
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
.handler{
width: 3px;
height: 100%;
padding: 0px 0;
top: 0;
background: red;
cursor: col-resize
}
<div class="wrapper">
<div class="box">A</div>
<div class="handler"></div>
<div class="box">B</div>
</div>
<console></console>
No limits are applied here, this can be enhanced with CSS only, using min-width and other similar rules, and the float values can be retrieved to create range sliders and more, this way.

How to make this tooltip like this with pure javascript

I need to use JS no JQuery plugins to make a simple tooltip like on the image below.
Click on ? image should open this tooltip and click again on the same image to close it.
I think that it's simple for someone with good JS knowledge but I can't do it anyway :(
This is something that I have tried I know it's not too much but I am simply stuck.
How to display it like on the image, how to hide it when it's open and how to add that little triangle in the corner?
myfiddle
<img id="info" src="http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png"/>
<div id="ttip">bla bla</div>
document.getElementById('info').addEventListener('click', function(){
// how to check if it's visible so I can close tooltip
document.getElementById('ttip').style.display="block";
});
#info{margin-left:100px;margin-top:50px;}
#ttip
{
width: 280px;
z-index: 15001;
top: 0px;
left: 0px;
display: none;
border-color: #666;
background-color: #fff;
color: #666;
position: relative;
border: 1px solid #666;
padding: 15px 9px 5px 9px;
text-align: left;
word-wrap: break-word;
overflow: hidden;
}
Clean up the css and this will basically do it:
<script>
function doTip(e){
var elem = e.toElement;
if(elem.getAttribute('data-tip-on') === 'false') {
elem.setAttribute('data-tip-on', 'true');
var rect = elem.getBoundingClientRect();
var tipId = Math.random().toString(36).substring(7);
elem.setAttribute('data-tip-id', tipId);
var tip = document.createElement("div");
tip.setAttribute('id', tipId);
tip.innerHTML = elem.getAttribute('data-tip');
tip.style.top = rect.bottom+ 10 + 'px';
tip.style.left = (rect.left-200) + 'px';
tip.setAttribute('class','tip-box');
document.body.appendChild(tip);
} else {
elem.setAttribute('data-tip-on', 'false');
var tip = document.getElementById(elem.getAttribute('data-tip-id'));
tip.parentNode.removeChild(tip);
}
}
function enableTips(){
var elems = document.getElementsByClassName('quick-tip');
for(var i = 0; i < elems.length; i++) {
elems[0].addEventListener("click", doTip, false);
}
}
window.onload = function(){
enableTips();
}
</script>
<style>
.quick-tip {
background: black;
color: #fff;
padding: 5px;
cursor: pointer;
height: 15px;
width: 15px;
text-align: center;
font-weight: 900;
margin-left: 350px;
}
.tip-box {
/* change dimensions to be whatever the background image is */
height: 50px;
width: 200px;
background: grey;
border: 1px solid black;
position: absolute;
}
</style>
<div class="quick-tip" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false">?</div>
<script>enableTips(); //might be required for jsfiddle, especially with reloads.</script>
Edit: fixed formatting and a bug. jsfiddle: http://jsfiddle.net/u93a3/
Proof of concept:
The following markup in HTML: Create a div with class tooltip, add image and a div with class info with all text (can be multiple paragraphs if needed, scollbars is shown if necessary):
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
The div.info is set to display:none in CSS.
When the page is loaded a pure javascript is running that draws an image of a triangle on a canvas-element, and then creates a div-element where the triangle is set as a background. Then, for every div.tooltip:
add a click-eventhandler to the image
replace the div.info with a div.info_container
add a clone of the triangle-div to div.info_container
add the original div.info to div.info_container
You can test it with this fiddle. It is tested successfully on FF25, Chrome31, IE10, Opera 12&18.
<!doctype html>
<html>
<head>
<script>
"use strict";
function click(event) {
var elem = this.parentNode.querySelector('div.info_container');
if (elem) elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
}
function toolify() {
var idx,
len,
elem,
info,
text,
elements = document.querySelectorAll('div.tooltip'),
canvas,
imgurl,
pointer,
tipHeight = 20,
tipWidth = 20,
width = 200,
height = 100,
ctx;
// Create a canvas element where the triangle will be drawn
canvas = document.createElement('canvas');
canvas.width = tipHeight;
canvas.height = tipWidth;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000'; // Border color
ctx.fillStyle = '#fff'; // background color
ctx.lineWidth = 1;
ctx.translate(-0.5,-0.5); // Move half pixel to make sharp lines
ctx.beginPath();
ctx.moveTo(1,canvas.height); // lower left corner
ctx.lineTo(canvas.width, 1); // upper right corner
ctx.lineTo(canvas.width,canvas.height); // lower right corner
ctx.fill(); // fill the background
ctx.stroke(); // stroke it with border
//fix bottom row
ctx.fillRect(0,canvas.height-0.5,canvas.width-1,canvas.height+2);
// Create a div element where the triangel will be set as background
pointer = document.createElement('div');
pointer.style.width = canvas.width + 'px';
pointer.style.height = canvas.height + 'px';
pointer.innerHTML = ' ' // non breaking space
pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
pointer.style.position = 'absolute';
pointer.style.top = '2px';
pointer.style.right = '1px';
pointer.style.zIndex = '1'; // place it over the other elements
for (idx=0, len=elements.length; idx < len; ++idx) {
elem = elements[idx];
elem.querySelector('img').addEventListener('click',click);
text = elem.querySelector('div.info');
// Create a new div element, and place the text and pointer in it
info = document.createElement('div');
text.parentNode.replaceChild(info,text);
info.className = 'info_container';
info.appendChild(pointer.cloneNode());
info.appendChild(text);
//info.addEventListener('click',click);
}
}
window.addEventListener('load',toolify);
</script>
<style>
div.tooltip
{
position:relative;
display:inline-block;
width:300px;
text-align:right;
}
div.tooltip > div.info
{
display:none;
}
div.tooltip div.info_container
{
position:absolute;
right:20px;
width:200px;
height:100px;
display:none;
}
div.tooltip div.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}
</style>
</head>
<body>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
</div>
</div>
</body>
</html>

Applying background color based on scrolling content

Here is my JsFiddle
I want to apply background-color change property to circle when the window slides. Like in the beginning only first circle will have background-color. and when the images slides to second screen the second circle will have only color.
Can anybody guide me how to achieve that.
JQuery:
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
}
}, 3000);
});
Here's a simple solution of your problem: http://jsfiddle.net/pjvCw/44/ but....
The way you're doing galleries is quite wrong.
You have a really sensitive CSS full of margin bugs (see in CSS code),
you calculate all by hand, which will just complicate your life one day if you'll get to add images, change widths etc...
Your buttons are positioned really wrongly, and again you don't even need to manually add them in your HTML. Let jQuery do all the job for you:
Calculate margins, widths,
Get the number of slides
generate buttons,
Make your buttons clickable
Pause gallery on mouseenter (loop again on mouseleave)
LIVE DEMO
This is the way you should go with your slider:
HTML:
<div class="galleryContainer"> <!-- Note this main 'wrapper' -->
<div class="gallery">
<div class="row">
<!-- ..your images.. -->
</div>
<div class="row">
<!-- ..your images.. -->
</div>
</div>
<div class="content-nav-control"></div> <!-- Let jQ create the buttons -->
</div>
Note the general gallery wrapper, it allows you with this CSS to make your buttons parent not move with the gallery.
CSS:
In your code, using display:inline-block; adds 4px margin to your elements, ruining your math. So you just need to apply font-size:0; to remove that inconvenience.
As soon I did that the math was working and the right width was than 340px, having 5px border for your images and 20px margin.
.galleryContainer{
/* you need that one
// to prevent the navigation move */
position:relative; /* cause .content-nav-control is absolute */
background-color: #abcdef;
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery{
position:relative;
overflow: hidden; /* "overflow" is enough */
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery .row {
white-space: nowrap;
font-size:0; /* prevent inline-block 4px margin issue */
}
.gallery img {
display: inline-block;
margin-left: 20px;
margin-top: 20px;
}
.normalimage {
height: 80px;
width: 50px;
border: 5px solid black;
}
.wideimage {
height: 80px;
width: 130px;
border: 5px solid black;
}
img:last-of-type {
margin-right:20px;
}
.content-nav-control {
position: absolute;
width:100%; /* cause it's absolute */
bottom:10px;
text-align:center; /* cause of inline-block buttons inside*/
font-size:0; /* same trick as above */
}
.content-nav-control > span {
cursor:pointer;
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin: 0 2px; /* BOTH MARGINS LEFT AND RIGHT */
}
.content-nav-control > span.active{
background:blue;
}
And finally:
$(function () { // DOM ready shorty
var $gal = $('.gallery'),
$nav = $('.content-nav-control'),
galSW = $gal[0].scrollWidth, // scrollable width
imgM = parseInt($gal.find('img').css('marginLeft'), 10), // 20px
galW = $gal.width() - imgM, // - one Margin
n = Math.round(galSW/galW), // n of slides
c = 0, // counter
galIntv; // the interval
for(var i=0; i<n; i++){
$nav.append('<span />'); // Create circles
}
var $btn = $nav.find('span');
$btn.eq(c).addClass('active');
function anim(){
$btn.removeClass('active').eq(c).addClass('active');
$gal.stop().animate({scrollLeft: galW*c }, 400);
}
function loop(){
galIntv = setInterval(function(){
c = ++c%n;
anim();
}, 3000);
}
loop(); // first start kick
// MAKE BUTTONS CLICKABLE
$nav.on('click', 'span', function(){
c = $(this).index();
anim();
});
// PAUSE ON GALLERY MOUSEENTER
$gal.parent('.galleryContainer').hover(function( e ){
return e.type=='mouseenter' ? clearInterval(galIntv) : loop() ;
});
});
"- With this solution, What can I do now and in the future? -"
Nothing! just freely add images into your HTML and play, and never again have to take a look at your backyard :)
Try this: http://jsfiddle.net/yerdW/1/
I added a line that gets the scrollLeft and divides it by your width (331px) to get the position and use that to select the 'active' circle:
$(".circle").removeClass("coloured");
position = Math.ceil($(".gallery").scrollLeft()/331 + 2);
if(position > $(".circle").length){
position = 1; // yes...
}
$(".content-nav-control div:nth-child("+position+")").addClass("coloured");
Red background for active circle:
.coloured {
background : red;
}
Note that you should initialise with the first circle already having the .coloured class applied.
Here you go: http://jsfiddle.net/pjvCw/41/
i added new class
.selected
{
background-color: red;
}
and modified some js code
Here is your jsfiddle edited http://jsfiddle.net/pjvCw/45/
var scrolled = 0;
var circles = $(".circle");
var colorCircle = function(index) {
for(var i=0; i<circles.length; i++) {
if(i == index) {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 1)");
} else {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 0)");
}
}
}
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
colorCircle(++scrolled);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
colorCircle(scrolled = 0);
}
}, 3000);
colorCircle(0);
});
I added a transition to the .circle class, so it looks a little bit better:
.circle {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin-right: 5px;
transition: background-color 700ms;
-webkit-transition: background-color 700ms;
}

Categories