Html into wordpress theme - javascript

I need to make a fixed bottom footer to my WordPress web, with some buttons including js with a popover. I've Pillar Theme and I only need to make this change. I need to put it into my footer.php. But when I try, nothing works. I do not know if this is the best way to do that. Here is the code that I do for the footer:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Styles just for demo -->
<style>
#font-face {
font-family: 'social-icons';
font-weight: normal;
font-style: normal;
src: url('font/social.eot?44259375');
src: url('font/social.eot?44259375#iefix') format('embedded-opentype'), url('font/social.woff?44259375') format('woff'), url('font/social.ttf?44259375') format('truetype'), url('font/social.svg?44259375#social') format('svg');
}
/* Share button
***********************************************/
.need-share-button {
position: relative;
display: inline-block;
}
.need-share-button_dropdown {
position: absolute;
z-index: 10;
visibility: hidden;
overflow: hidden;
width: 240px;
-webkit-transition: .3s;
transition: .3s;
-webkit-transform: scale(.1);
-ms-transform: scale(.1);
transform: scale(.1);
text-align: center;
opacity: 0;
-webkit-border-radius: 4px;
border-radius: 4px;
}
.need-share-button-opened .need-share-button_dropdown {
visibility: visible;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
opacity: 1;
}
.need-share-button_link {
display: inline-block;
width: 40px;
height: 40px;
line-height: 40px;
cursor: pointer;
text-align: center;
}
.need-share-button_link:after {
font: normal normal normal 16px/1 'social-icons';
text-align: center;
text-transform: none;
speak: none;
}
.need-share-button_link:hover {
-webkit-transition: .3s;
transition: .3s;
opacity: .7;
}
/* Dropdown position
***********************************************/
.need-share-button_dropdown-top-center {
bottom: 100%;
left: 50%;
margin-bottom: 10px;
}
/* Default theme
***********************************************/
.need-share-button-default .need-share-button_button {
display: inline-block;
margin-bottom: 0;
padding: 20px;
font-size: 14px;
line-height: 1.42857143;
font-weight: 400;
color: white;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-align: center;
vertical-align: middle;
white-space: nowrap;
background-image: url("share.png") no-repeat;
}
.need-share-button-default .need-share-button_button span {
background-image: url("share.png") no-repeat;
}
.need-share-button-default .need-share-button_button:hover {
color: #737373;
}
/* Network buttons
***********************************************/
.need-share-button_mailto {
color: #efbe00;
}
.need-share-button_mailto:after {
content: '\e80a';
}
.need-share-button_mailto.need-share-button_link-box {
color: #fff;
background: #efbe00;
}
.need-share-button_twitter {
color: #00acec;
}
.need-share-button_twitter:after {
content: '\e813';
}
.need-share-button_twitter.need-share-button_link-box {
color: #fff;
background: #00acec;
}
.need-share-button_facebook {
color: #3b5998;
}
.need-share-button_facebook:after {
content: '\e80e';
}
.need-share-button_facebook.need-share-button_link-box {
color: #fff;
background: #3b5998;
}
.wrapper {
text-align: center;
}
footer {
background-color: black;
position: fixed;
bottom: 0;
width: 100%;
left: 0;
height: 60px;
}
footer .col-sm {
text-align: center;
}
a {
color: white;
text-decoration: none;
}
footer .col-sm > span {
padding: 7px 0 0px;
display: inline-block;
}
footer .col-sm > span > a:hover {
color: #737373;
text-decoration: none;
}
#homefooter a{
background-image: url("home.png");
background-repeat: no-repeat;
padding-bottom: 35px;
}
#donarfooter a {
background-image: url("donar.png");
background-repeat: no-repeat;
padding-bottom: 35px;
}
footer a span {
visibility: hidden;
}
/* ------------------------------------ MEDIA QUERIES -------------------------------------------*/
#media (max-width: 900px){
footer .col-sm {
width: 25%;
}
footer span {
padding: 0 !important;
}
}
/* ------------------------------------ MEDIA QUERIES -------------------------------------------*/
/* ------------------------------------ SEARCH STYLES -------------------------------------------*/
* {
box-sizing: border-box;
}
.openBtn {
background: #f1f1f1;
border: none;
padding: 10px 15px;
font-size: 20px;
cursor: pointer;
}
.openBtn:hover {
background: #bbb;
}
.overlay {
height: 100%;
width: 100%;
display: none;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.9);
}
.overlay-content {
position: relative;
top: 46%;
width: 80%;
text-align: center;
margin-top: 30px;
margin: auto;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
cursor: pointer;
color: white;
}
.overlay .closebtn:hover {
color: #ccc;
}
.overlay input[type=text] {
padding: 15px;
font-size: 17px;
border: none;
float: left;
width: 80%;
background: white;
}
.overlay input[type=text]:hover {
background: #f1f1f1;
}
.overlay button {
float: left;
width: 20%;
padding: 15px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.overlay button:hover {
background: #bbb;
}
/* ------------------------------------ SEARCH STYLES -------------------------------------------*/
</style>
</head>
<body>
<section>
<div id="myOverlay" class="overlay">
<span class="closebtn" onclick="closeSearch()" title="Close Overlay">×</span>
<div class="overlay-content">
<form action="/action_page.php">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
</section>
<footer class="fixed-bottom">
<div class="container-fluid" style="height: 100%">
<div class="row" style="height: 100%">
<div class="col-sm" id="homefooter">
<span>
<span>HOME</span>
</span>
</div>
<div class="col-sm" style="height: 100%; border-left: solid 0.5px white; border-right: solid 0.5px white">
<div class="wrapper">
<img src="share.png">
<div id="share-button-2" class="need-share-button-default" data-share-position="topCenter" data-share-icon-style="box" data-share-networks="Mailto,Twitter,Facebook"></div>
</div>
</div>
<div class="col-sm" id="donarfooter">
<span>
<span>CONTRIBUIR</span>
</span>
</div>
<div class="col-sm" id="donarfooter">
<span>
<button class="openBtn" onclick="openSearch()">BUSCAR</button>
</span>
</div>
</div>
</div>
</footer>
<script>
/***********************************************
needShareButton
- Version 1.0.0
- Copyright 2015 Dzmitry Vasileuski
- Licensed under MIT (http://opensource.org/licenses/MIT)
***********************************************/
(function() {
// share dropdown class
window.needShareDropdown = function(elem, options) {
// create element reference
var root = this;
root.elem = elem;
root.elem.className += root.elem.className.length ? ' need-share-button' : 'need-share-button';
/* Helpers
***********************************************/
// get title from html
root.getTitle = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:title"]') || document.querySelector('meta[name="twitter:title"]')) {
return content.getAttribute('content');
} else if (content = document.querySelector('title')) {
return content.innerText;
} else
return '';
} else {
if (content = document.title)
return content.innerText;
else
return '';
}
};
// get image from html
root.getImage = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:image"]') || document.querySelector('meta[name="twitter:image"]')) {
return content.getAttribute('content');
} else
return '';
} else
return '';
};
// get description from html
root.getDescription = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:description"]') || document.querySelector('meta[name="twitter:description"]') || document.querySelector('meta[name="description"]')) {
return content.getAttribute('content');
} else
return '';
} else {
if (content = document.getElementsByTagName('meta').namedItem('description'))
return content.getAttribute('content');
else
return '';
}
};
// share urls for all networks
root.share = {
'mailto' : function() {
var url = 'mailto:?subject=' + encodeURIComponent(root.options.title) + '&body=Thought you might enjoy reading this: ' + encodeURIComponent(root.options.url) + ' - ' + encodeURIComponent(root.options.description);
window.location.href = url;
},
'twitter' : function() {
var url = root.options.protocol + 'twitter.com/home?status=';
url += encodeURIComponent(root.options.title) + encodeURIComponent(root.options.url);
root.popup(url);
},
'facebook' : function() {
var url = root.options.protocol + 'www.facebook.com/sharer/share.php?';
url += 'u=' + encodeURIComponent(root.options.url);
url += '&title=' + encodeURIComponent(root.options.title);
root.popup(url);
},
}
// open share link in a popup
root.popup = function(url) {
// set left and top position
var popupWidth = 500,
popupHeight = 400,
// fix dual screen mode
dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left,
dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top,
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width,
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height,
// calculate top and left position
left = ((width / 2) - (popupWidth / 2)) + dualScreenLeft,
top = ((height / 2) - (popupHeight / 2)) + dualScreenTop,
// show popup
shareWindow = window.open(url,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + popupWidth + ', height=' + popupHeight + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
shareWindow.focus();
}
}
/* Set options
***********************************************/
// create default options
root.options = {
shareButtonClass: false, // child selector of custom share button
iconStyle: 'default', // default or box
boxForm: 'horizontal', // horizontal or vertical
position: 'bottomCenter', // top / middle / bottom + Left / Center / Right
buttonText: 'COMPARTIR',
protocol: ['http', 'https'].indexOf(window.location.href.split(':')[0]) === -1 ? 'https://' : '//',
url: window.location.href,
title: root.getTitle(),
image: root.getImage(),
description: root.getDescription(),
networks: 'Mailto,Twitter,Facebook'
}
// integrate data attribute options
for (var option in root.elem.dataset) {
// replace only 'share-' prefixed data-attributes
if (option.match(/share/)) {
var new_option = option.replace(/share/, '');
if (!new_option.length) {
continue;
}
new_option = new_option.charAt(0).toLowerCase() + new_option.slice(1);
root.options[new_option] = root.elem.dataset[option];
}
}
// convert networks string into array
root.options.networks = root.options.networks.toLowerCase().split(',');
/* Create layout
***********************************************/
// create dropdown button if not exists
if (root.options.shareButtonClass) {
for (var i = 0; i < root.elem.children.length; i++) {
if (root.elem.children[i].className.match(root.options.shareButtonClass))
root.button = root.elem.children[i];
}
}
if (!root.button) {
root.button = document.createElement('span');
root.button.innerText = root.options.buttonText;
root.elem.appendChild(root.button);
}
root.button.className += ' need-share-button_button';
// show and hide dropdown
root.button.addEventListener('click', function(event) {
event.preventDefault();
if (!root.elem.className.match(/need-share-button-opened/)) {
root.elem.className += ' need-share-button-opened';
} else {
root.elem.className = root.elem.className.replace(/\s*need-share-button-opened/g,'');
}
});
// create dropdown
root.dropdown = document.createElement('span');
root.dropdown.className = 'need-share-button_dropdown';
root.elem.appendChild(root.dropdown);
// set dropdown position
setTimeout(function() {
switch (root.options.position) {
case 'topCenter':
root.dropdown.className += ' need-share-button_dropdown-top-center';
root.dropdown.style.marginLeft = - root.dropdown.offsetWidth / 2 + 'px';
break
}
},1);
// fill fropdown with buttons
var iconClass = root.options.iconStyle == 'default' ? 'need-share-button_link need-share-button_' : 'need-share-button_link-' + root.options.iconStyle + ' need-share-button_link need-share-button_';
for (var network in root.options.networks) {
var link = document.createElement('span');
network = root.options.networks[network];
link.className = iconClass + network;
link.dataset.network = network;
root.dropdown.appendChild(link);
// add share function to event listener
link.addEventListener('click', function() {
root.share[this.dataset.network]();
});
}
}
})();
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
new needShareDropdown(document.getElementById('share-button-2'));
</script>
<script>
function openSearch() {
document.getElementById("myOverlay").style.display = "block";
}
function closeSearch() {
document.getElementById("myOverlay").style.display = "none";
}
</script>
</body>
</html>

You can try Sticky footer with jQuery. Add this code in your js file.
var $ = jQuery.noConflict();
jQuery(document).ready(function($){
/* sticky footer function */
StickyFooter()
});
/* Script on resize */
jQuery(window).resize(function($) {
/* sticky footer function */
StickyFooter();
});
/* Script on load
----------------------------------*/
jQuery(window).load(function($) {
/* sticky footer function */
StickyFooter();
});
/* Sticky Footer Function */
function StickyFooter(){
var Stickyfooter = jQuery( 'footer' ).outerHeight()
jQuery('#wrapper').css('margin-bottom',-Stickyfooter) /* Here #wrapper is your main <div> of <body> */
jQuery('#wrapper').css('padding-bottom',Stickyfooter)
}

Related

Template Literal Function not working as expected

I have a function that turns an array into modal window links as a template literal.
The code that creates the links works fine outside of the function
But once it gets rendered in the function it no longer works. I can't find any errors, but it does NOT work.
However, if I copy the HTML that the function renders and save that as actual HTML, that works fine on its own.
A good chunk of the JavaScript portion of the code is posted below. A full version is on Codepen.
There are two sections in the example on Codepen:
The first section has the code as it's rendered by the function.
The second section is copied from the Elements tab in Developer Tools and saved as actual HTML.
"use strict";
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
let modal = e.currentTarget;
if (modal.dataset.target) {
let modalID = modal.dataset.target;
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
let modalLink = "";
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>
`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
My apologies in advance for it not being stripped down to just the bare minimum. But in order to replicate the problem, it required more code than it probably should have had. I've been reworking this for the better part of a day without any insight as to what the real problem is. I've been creating functions using template literals just like this for years now, usually with a high success rate. Whatever the problem is, I need to know so I can get past it. The only anomaly that I spotted is that–in the version on Codepen–the only thing that doesn't work in that version is once the modal is displayed clicking on the background does not dismiss the modal like it does elsewhere. If that's significant as to what the problem may be, I'm not sure what the connection is.
Usually when I take the time to painstakingly write everything out like this I typically either spot the problem or figure out an alternative solution so there's no need to actually post a question, but this does not appear to be one of those times. As always, your help is very much appreciated!
The issue appears to just be timing. Your code is executed in order, and the first part gets all of the modal buttons on the page and sets the appropriate event listeners. Then the second part of your code adds 2 modal buttons, which were not present earlier.
By simply wrapping the first part of your code in a function and calling it later (or swapping the order of those two parts of code), everything works as expected.
"use strict";
const _InitModal = () => {
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
let modal = e.currentTarget;
console.log("modal = " + modal);
if (modal.dataset.target) {
let modalID = modal.dataset.target;
console.log("modal.dataset.target = " + modal.dataset.target);
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
console.log(`modal.dataset.header = ${modal.dataset.header}`);
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
// e.preventDefault();
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
console.log("e=" + e);
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
}
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
let modalLink = "";
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
_InitModal();
.modal-background {
font-family: sans-serif;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: none;
overflow: auto;
background-color: rgba(0, 0, 0, 0.9);
z-index: 9999;
background: rgba(55, 55, 55, 0.6);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.modal-window {
position: relative;
background-color: #ffffff;
width: 50%;
margin: 10% auto;
border-radius: 0.5rem;
padding: 0.75rem;
border: 1px groove #ccc;
/* box-shadow: 1px 1px 1px #999, 2px 2px 2px #000; */
}
.close-modal:hover,
.close-modal:focus {
color: rgba(255, 255, 255, 1);
cursor: pointer;
background: red;
transition: 1s;
text-shadow: 1px 1px 1px #999, 2px 2px 2px #000;
}
button.close-modal {
position: absolute;
top: -0.75rem;
right: -0.75rem;
padding: 0.05rem 0.75rem;
background: #999;
color: #ccc;
border-radius: 50%;
border: none;
outline: none;
-webkit-transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
-webkit-animation-name: animatebottom;
-webkit-animation-duration: 1.5s;
animation-name: animatebottom;
animation-duration: 1.5s;
}
button.close-modal::before {
content: "\D7";
font-size: 2rem;
}
.modal-window {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.5s;
animation-name: animatetop;
animation-duration: 0.5s;
}
.modal-header {
height: 30px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-header h1 {
font-size: 1.1rem;
}
.modal-footer {
height: 20px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-content {
background-color: #fff;
height: calc(100% - 70px);
border-radius: 0.5rem;
border: 0.1rem groove #ddd;
overflow: hidden;
}
.button-footer {
background: #fff;
border-radius: 0.5rem;
border: 1px outset #aaa;
padding: 0.2rem;
color: #999;
transition: 1s;
cursor: pointer;
}
.button-footer:hover {
background: #fdfdfd;
color: #555;
border: 1px inset #ddd;
text-shadow: 0.05rem 0.05rem 0.05rem #ccc, 0.055rem 0.055rem 0.055rem #999,
0.06rem 0.06rem 0.06rem #333;
transition: 1s;
}
.close-btn:hover {
color: white;
background: #f00;
cursor: pointer;
}
#modal_iframe {
width: 100%;
height: 100%;
}
button.modal-button {
border-radius: 0.5rem;
border: 0px solid #aaa;
padding: 0;
cursor: pointer;
}
.modal-button-img {
border-radius: 0.5rem;
border: 0.1rem groove #444;
cursor: pointer;
}
.sepia:hover {
filter: sepia(150%);
}
/*
.none {
display: none;
}
*/
#-webkit-keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#-webkit-keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
#keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
.container {
border-radius: 0.5rem;
border: 1px solid #aaa;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
font-family: sans-serif;
}
main,
aside {
font-family: sans-serif;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
}
h2 {
text-align: center;
font-family: sans-serif;
font-weight: normal;
font-size: 1.2rem;
}
span {
font-size: 75%;
background: #ffff0055;
}
<div id="modal_window" class="modal-background">
<div class="modal-window">
<button class="close-modal" data-dismiss="modal"></button>
<div class="modal-header"></div>
<div class="modal-content">
<iframe src="#" id="modal_iframe" frameborder="0">If you'd have had a real browser, I wouldn't be boring you with this now...</iframe>
</div>
<div class="modal-footer"><button class="button-footer">Open In New Tab</button></div>
</div>
</div>
<div class="container">
<h2><code>main</code> Content Rendered By JavaScript</h2>
<main>
Main
</main>
<span>working now</span>
</div>

How to make the image of specific html div or how can I take screenshot of specific area in JS? [duplicate]

I want to Generate and Download Screenshot of webpage without lossing the styles. I have a web page .In that web page i have a download button . When user click on download button then the screen shot of entire Page need to download as image in user computer . How can i do this ?
Please check my code
Index.html
<html>
<body>
<link href="style.css" rel="stylesheet">
<h1>Scrrenshot</h1>
<form class="cf">
<div class="half left cf">
<input type="text" id="input-name" placeholder="Name">
<input type="email" id="input-email" placeholder="Email address">
<input type="text" id="input-subject" placeholder="Subject">
</div>
<div class="half right cf">
<textarea name="message" type="text" id="input-message" placeholder="Message"></textarea>
</div>
<input type="submit" value="Submit" id="input-submit">
</form>
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
</body>
<script>
(function (exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype
|| nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>
</html>
style.css
#import "compass/css3";
#import url(https://fonts.googleapis.com/css?family=Merriweather);
$red: #e74c3c;
*,
*:before,
*:after {
#include box-sizing(border-box);
}
html, body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
h1 {
text-align: center;
color: #a8a8a8;
#include text-shadow(1px 1px 0 rgba(white, 1));
}
form {
border: 2px solid blue;
margin: 20px auto;
max-width: 600px;
padding: 5px;
text-align: center;
}
input, textarea {
border:0; outline:0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
textarea {
height: 126px;
}
}
.half {
float: left;
width: 48%;
margin-bottom: 1em;
}
.right { width: 50%; }
.left {
margin-right: 2%;
}
#media (max-width: 480px) {
.half {
width: 100%;
float: none;
margin-bottom: 0;
}
}
/* Clearfix */
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
.half.left.cf > input {
margin: 5px;
}
For this i used the method [http://www.xpertdeveloper.com/2012/10/webpage-screenshot-with-html5-js/] , here screenshot is generated but without style also it is not downloading . Please help , is there any jQuery library available for this?
You can achieve this using the following JavaScript libraries ...
html2canvas ( for taking screenshot of webpage )
FileSave.js ( for downloading the screenshot as an image )
ᴅᴇᴍᴏ
(function(exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function(el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
var wrapper = document.getElementById('wrapper');
html2canvas(wrapper, {
onrendered: function(canvas) {
canvas.toBlob(function(blob) {
saveAs(blob, 'myScreenshot.png');
});
}
});
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function(e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
screenshotPage();
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
#import url(https://fonts.googleapis.com/css?family=Merriweather);
$red: #e74c3c;
*,
*:before,
*:after {
#include box-sizing(border-box);
}
html,
body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
h1 {
text-align: center;
color: #a8a8a8;
#include text-shadow(1px 1px 0 rgba(white, 1));
}
form {
border: 2px solid blue;
margin: 20px auto;
max-width: 600px;
padding: 5px;
text-align: center;
}
input,
textarea {
border: 0;
outline: 0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
textarea {
height: 126px;
}
}
.half {
float: left;
width: 48%;
margin-bottom: 1em;
}
.right {
width: 50%;
}
.left {
margin-right: 2%;
}
#media (max-width: 480px) {
.half {
width: 100%;
float: none;
margin-bottom: 0;
}
}
/* Clearfix */
.cf:before,
.cf:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.cf:after {
clear: both;
}
.half.left.cf > input {
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="wrapper">
<h1>Scrrenshot</h1>
<form class="cf">
<div class="half left cf">
<input type="text" id="input-name" placeholder="Name">
<input type="email" id="input-email" placeholder="Email address">
<input type="text" id="input-subject" placeholder="Subject">
</div>
<div class="half right cf">
<textarea name="message" type="text" id="input-message" placeholder="Message"></textarea>
</div>
<input type="submit" value="Submit" id="input-submit">
</form>
</div>
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
I found that dom-to-image did a much better job than html2canvas. See the following question & answer: https://stackoverflow.com/a/32776834/207981
If you're looking to download the image(s) you'll want to combine it with FileSaver.js (already mentioned here), and if you want to download a zip with multiple image files all generated client-side take a look at jszip.
Few options for this
either use this
<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<a download="logo.png" href="http://localhost/folder/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/folder/img/logo.png">
</a>
</body>
</html>
or You can use Mordernizr
or maybe this works
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
refer to this link aswell
[1] http://www.w3schools.com/tags/att_a_download.asp

Unable to reset JavaScript bar graph

I have a bar graph created in JavaScript to display values using colors. I am having trouble resetting the bar graph. Basically what needs to happen is when the "reset" button is clicked, all bars clear values and reset to "0". Then the button needs to give the option to "Generate" and the previous values are shown again. Also, this is my first time using constant velocity to ease the bars up and down as the button is clicked to give it a little flair. Not sure what I am missing to have the data clear and be set to zero on the bottom line of the graph while using constant velocity to make it ease down and when button is clicked to restore the values to previous state. Any help is appreciated. Here is the code so far:
HTML
/*
* Some base values.
*/
var millisecondsPerFrame = 30;
/*
* Helper function for managing button event handlers.
*/
var setupButton = function(button, label, onclickHandler) {
button.value = label;
button.onclick = onclickHandler;
button.disabled = false;
};
var startConstantVelocityAnimation = function() {
// Grab the desired velocity.
var velocity = parseFloat(document.getElementById("chart").value);
// Grab the object to animate, and initialize if necessary.
var colors = document.getElementById("colors");
chart.style.bottom = chart.style.bottom || "0px";
// Start animating.
var intervalID = setInterval(function() {
var newBottom = parseInt(box.style.bottom) + velocity;
if ((newBottom < 0) || (newBottom > maxBottom)) {
velocity = -velocity;
} else {
chart.style.bottom = newBottom + "px";
}
}, millisecondsPerFrame);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"), "Reset", function() {
clearInterval(intervalID);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"),
"Generate", startConstantVelocityAnimation);
});
};
window.onload = function() {
// Set up the initial event handlers.
document.getElementById("Reset").onclick = startConstantVelocityAnimation;
};
**
* Graph JS Code ** *
function createBarChart(data) {
// Start with the container.
var chart = document.createElement("div");
// The container must have position: relative.
chart.style.position = "relative";
// The chart's height is the value of its largest
// data item plus a little margin.
var height = 0;
for (var i = 0; i < data.length; i += 1) {
height = Math.max(height, data[i].value);
}
chart.style.height = (height + 10) + "px";
// Give the chart a bottom border.
chart.style.borderBottomStyle = "solid";
chart.style.borderBottomWidth = "1px";
// Iterate through the data.
var barPosition = 0;
// We have a preset bar width for the purposes of this
// example. A full-blown chart module would make this
// customizable.
var barWidth = 48.30;
for (i = 0; i < data.length; i += 1) {
// Basic column setup.
var dataItem = data[i];
var bar = document.createElement("div");
bar.style.position = "absolute";
bar.style.left = barPosition + "px";
bar.style.width = barWidth + "px";
bar.style.backgroundColor = dataItem.color;
bar.style.height = dataItem.value + "px";
bar.style.borderStyle = "ridge";
bar.style.borderColor = dataItem.color;
// Visual flair with CSS Level 3 (for maximum compatibility
// we set multiple possible properties to the same value).
// Hardcoded values here just for illustration; a
// full module would allow major customizability.
bar.style.MozBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.WebkitBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.boxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.MozBorderRadiusTopleft = "8px";
bar.style.WebkitBorderTopLeftRadius = "8px";
bar.style.borderTopLeftRadius = "8px";
bar.style.MozBorderRadiusTopright = "8px";
bar.style.WebkitBorderTopRightRadius = "8px";
bar.style.borderTopRightRadius = "8px";
bar.style.backgroundImage =
"-moz-linear-gradient(" + dataItem.color + ", black)";
bar.style.backgroundImage =
"-webkit-gradient(linear, 0% 0%, 0% 100%," +
"color-stop(0, " + dataItem.color + "), color-stop(1, black))";
bar.style.backgroundImage =
"linear-gradient(" + dataItem.color + ", black)";
// Recall that positioning properties are treated *relative*
// to the corresponding sides of the containing element.
bar.style.bottom = "-1px";
chart.appendChild(bar);
// Move to the next bar. We provide an entire bar's
// width as space between columns.
barPosition += (barWidth * 2);
}
return chart;
};
window.onload = function() {
var colors = [{
color: "red",
value: 40
},
{
color: "blue",
value: 10
},
{
color: "green",
value: 100
},
{
color: "black",
value: 65
},
{
color: "yellow",
value: 75
},
{
color: "purple",
value: 120
},
{
color: "grey",
value: 121
},
{
color: "orange",
value: 175
},
{
color: "olive",
value: 220
},
{
color: "maroon",
value: 275
},
{
color: "brown",
value: 300
},
{
color: "teal",
value: 15
}
];
var chart = createBarChart(colors);
document.querySelector("#wrapper").appendChild(chart); // keeps chart inside wrapper div
};
#wrapper {
margin-left: auto;
margin-right: auto;
width: 85%;
border: groove;
border-color: white;
padding: 2px;
}
#loginwrap {
margin-left: auto;
margin-right: auto;
padding: 3px;
text-align: center;
}
body {
font-family: Georgia;
padding: 10px;
background: #f1f1f1;
font-weight: bold;
}
/* top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* three columns next to each other */
.column1 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
.column2 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #bbb;
}
.column3 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Card-like background for each section */
.card {
background-color: white;
padding: 30px;
margin-top: 20px;
overflow: auto;
}
/* Align about section image to right */
.aboutimg {
float: right;
}
/* Footer */
.footer {
padding: 20px;
background: #ddd;
margin-top: 20px;
}
.copyright {
margin-right: auto;
margin-left: auto;
width: 85%;
text-align: center;
font-size: 10px;
padding: 5px;
}
/*Chart Color Legend*/
.legend .legend-scale ul {
margin: 0;
padding: 0;
float: left;
list-style: none;
}
.legend .legend-scale ul li {
display: block;
float: left;
width: 50px;
margin-bottom: 6px;
text-align: center;
font-size: 80%;
list-style: none;
}
.legend ul.legend-labels li span {
display: block;
float: left;
height: 15px;
width: 50px;
}
.legend a {
color: #777;
}
.subs {
font-size: 10px;
font-style: italic;
padding: 5px;
text-align: center;
}
.reset-button {
text-align: right;
padding-top: 2px;
padding-right: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Issue Tracking System" />
<meta name="author" content="S Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script src="js/animation.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Sales Subscription Dashboard</h2>
<div class="topnav">
Home
Tracker Login
</div>
<div>
<div class="legend">
<div class="legend-scale">
<div class="reset-button">
<input type="button" value="Reset Graph" id="Reset">
</div>
<ul class="legend-labels">
<li><span></span>40</li>
<li><span></span>10</li>
<li><span></span>100</li>
<li><span></span>65</li>
<li><span></span>75</li>
<li><span></span>120</li>
<li><span></span>121</li>
<li><span></span>175</li>
<li><span></span>220</li>
<li><span></span>275</li>
<li><span></span>300</li>
<li><span></span>15</li>
</ul>
</div>
</div>
<div class="legend">
<div class="legend-scale">
<ul class="legend-labels">
<li><span style='background:red;'></span>Jan</li>
<li><span style='background:blue;'></span>Feb</li>
<li><span style='background:green;'></span>March</li>
<li><span style='background:black;'></span>Apr</li>
<li><span style='background:yellow;'></span>May</li>
<li><span style='background:purple;'></span>June</li>
<li><span style='background:grey;'></span>July</li>
<li><span style='background:orange;'></span>Aug</li>
<li><span style='background:olive;'></span>Sept</li>
<li><span style='background:maroon;'></span>Oct</li>
<li><span style='background:brown;'></span>Nov</li>
<li><span style='background:teal;'></span>Dec</li>
</ul>
</div>
</div>
<br><br><br><br>
<hr>
<div class="subs">***Subscribers in Thousands***</div>
<script src="js/subscriptions_graph.js"></script>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>

Underline slide transition in buttons

I tried to search for tutorials on this effect. The effect that I wanted is an active underline (or border-bottom) under a link. When I click on a link, the underline will slide over to the next link and so on... One example is this question.
I know that what I have in html are buttons, not nav menu. So the coding would be different. I'm thinking that I might need to convert the buttons to nav menu if it doesn't work out.
Anyway, the problem is that I did try to use the example mentioned above to make the underline move to a clinked link. But it's not working...
Here's my code which is on codepen.
$(document).ready(function() {
$(".con-button").click(function(){
if(this.id == "c-all") {
$(".con-button").removeClass("active");
$("#c-all").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$(".con-button").removeClass("active");
$("#c-online").addClass("active");
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$(".con-button").removeClass("active");
$("#c-offline").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
})
getSteams();
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "maatukka", "Vinesauce", "brunofin", "comster404", "OgamingSC2"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.effect {
position: absolute;
left: 0;
transition: 0.4s ease-in-out;
}
.controls .effect {
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
height: 2px;
bottom: 5px;
background: #6441A4;
margin-left:/*-45px*/auto;
margin-right:/*-45px*/auto;
width: 33%;
}
button:nth-child(1).active ~ .effect {left: 0%;}
button:nth-child(2).active ~ .effect {left: 33%;}
button:nth-child(3).active ~ .effect {left: 66%;}
.divider hr {
border-top: 1px solid #6441A4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
I made sure that .active is working in Javascript but I still need help making the underline moving from one link to another when clicked. All I know is that it has something to do with the CSS. Any help or tutorials are appreciated.
You can use this simple technique if you can use jQuery. It is quite generic and you can use any html elements whether nav, buttons or simple div's. You just need to have an outer element that contains all your links.
The idea is to find the position and width of the clicked anchor tag and then apply the same(or after adding some modification) to the underline element. To make its movement smooth you can add transition for left and width properties of this underline element.
$("#outer-container a").on("click", function(e){
e.preventDefault();
var cssObj = {};
cssObj.left = $(this).position().left;
cssObj.width = $(this).outerWidth();
$("#outer-container #underline").css( cssObj );
});//a click()
$("#outer-container a").eq(0).trigger("click");
#outer-container
{
text-align: center;
position: relative;
}
#outer-container a
{
color: #333;
display: inline-block;
padding: 0 10px;
text-decoration: none;
}
#outer-container #underline
{
content: "";
display: block;
position: absolute;
bottom: 0;
left: 0;
height: 2px;
width: 100px;
background-color: #333;
transition: left 0.3s ease, width 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="outer-container">
One
Two
Three
Four
<span id="underline"></span>
</div><!--#outer-container-->
Checkout this,
$(document).ready(function() {
$(".con-button").click(function(){
if(this.id == "c-all") {
$(".con-button").removeClass("active");
$("#c-all").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$(".con-button").removeClass("active");
$("#c-online").addClass("active");
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$(".con-button").removeClass("active");
$("#c-offline").addClass("active");
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
})
getSteams();
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "maatukka", "Vinesauce", "brunofin", "comster404", "OgamingSC2"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.effect {
position: absolute;
left: 0;
transition: 0.4s ease-in-out;
}
.controls .effect {
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
height: 2px;
bottom: 5px;
background: #6441A4;
margin-left:/*-45px*/auto;
margin-right:/*-45px*/auto;
width: 33%;
}
button:nth-child(1).active ~ .effect {left: 0%;}
button:nth-child(2).active ~ .effect {left: 33%;}
button:nth-child(3).active ~ .effect {left: 66%;}
.divider hr {
border-top: 1px solid #6441A4;
}
.effect {
position: absolute;
left: 18%;
transition: 0.4s ease-in-out;
}
.controls button:nth-child(1).active ~ .effect {
left: 28%;
/* the middle of the first <a> */
}
.controls button:nth-child(2).active ~ .effect {
left: 50%;
/* the middle of the second <a> */
}
.controls button:nth-child(3).active ~ .effect {
left: 77%;
/* the middle of the third <a> */
}
.controls button:nth-child(4).active ~ .effect {
left: 93.5%;
/* the middle of the forth <a> */
}
.controls .effect {
width: 55px;
height: 2px;
bottom: 5px;
background: #00ABE8;
margin-left:-45px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
<div class="effect"></div>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
I have made changes in your code to make it work.

Javascript Slideshow Functions Not Working

I would please like an explanation to why the slideshow is not working. Below I have used an interval to perpetually change the slideshow, if userClick is false. The white and squared buttons (made of divs) are set to call upon two functions; slideRight() or slideLeft() and clicked(). When the buttons are clicked however, the clicked() function does not seem to change the variable, based on the data on top of the page.
<body>
<div class="page-wrapper">
<header>
<div class="headContent">
<h1 class="titleText">Slideshow</h1>
<h2 class="subTitleText">A slideshow made with JavaScript.</h2>
<p>userClick <span id="uc"></span></p>
</div>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
</ul>
</nav>
</header>
<div class="body-wrapper">
<h1 class="titleText">Slideshow</h1>
<div id="slideshow">
<div id="leftSlide" onclick="leftSlide(); clicked()"></div>
<div id="rightSlide" onclick="rightSlide(); clicked()"></div>
</div>
<p>The image is not invoked by a tag, but invoked by the background property using Javascript.</p>
</div>
<footer>
<p id="footerText">© 2017 <br>Designed by JastineRay</p>
</footer>
</div>
<script language="javascript">
// Slide function
var slide = ["minivan", "lifeinthecity", "sunsetbodyoflove"];
var slideTo = 1;
window.onload = getSlide();
// Previous Image
function leftSlide() {
if (slideTo != 0) {
slideTo = slideTo - 1;
} else if (slideTo == 0) {
slideTo = slide.length - 1;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
// Next Image
function rightSlide() {
if (slideTo != (slide.length - 1)) {
slideTo = slideTo + 1;
} else if (slideTo == (slide.length - 1)) {
slideTo = 0;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
function getSlide() {
imageURL = 'url(images/' + slide[slideTo] + '.jpg)';
document.getElementById("slideshow").style.backgroundImage = imageURL;
}
// Interval Slideshow & Check if user clicked (timeout)
var userClick = false;
window.onload = slideInterval(5000);
// Start Slideshow
function slideInterval(interval) {
while (userClick = false) {
setInterval(function() {
rightSlide();
}, interval)
}
}
// Stop Slideshow and start timeout
function clicked() {
userClick = true;
setTimeout(function() {
userClick = false;
slideInterval();
}, 2000)
}
window.onload = function() {
setInterval(document.getElementById("uc").innerHTML = userClick), 100
}
</script>
</body>
CSS coding below.
* {
margin: 0;
padding: 0;
}
.page-wrapper {
width: 100%;
}
// Class Styling
.titleText {
font-family: monospace;
font-size: 40px;
}
.subTitleText {
font-family: monospace;
font-size: 20px;
font-weight: normal;
}
// Header Styling
header {
height: 500px;
}
.headContent {
margin: 30px 7%;
}
// Navigation Styling
nav {
overflow: hidden;
}
nav ul {
background: black;
background: linear-gradient(#595959, black);
list-style-type: none;
font-size: 0;
padding-left: 13.33%;
margin: 40px 0;
}
nav ul li {
padding: 15px 20px;
border-right: 1px solid #595959;
border-left: 1px solid #595959;
color: white;
display: inline-block;
font-size: 20px;
font-family: sans-serif;
}
// Body Styling
.body-wrapper {
}
.body-wrapper > .titleText {
text-align: center;
font-size: 50px;
}
#slideshow {
overflow: hidden;
margin: 20px auto;
border: 2px solid blue;
height: 350px;
max-width: 800px;
background-size: cover;
background-position: center;
position: relative;
}
#leftSlide {
position: absolute;
left: 40px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
#rightSlide {
position: absolute;
left: 100px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
// Footer Styling
Try changing the checking part to:
window.onload = function() {
setInterval(function () {
document.getElementById("uc").innerHTML = userClick;
}, 100);
}
The first argument of setInterval has to be a function (something that can be called), not a generic piece of code.

Categories

Resources