I want to make a html button that appears when you scroll down and when clicked it shows a random blogger post.
I have code to make it appear when you scroll down and code for a button that shows a random post. But I don't know how to make them work together.
This is my scroll button code, below is random post code. I don't know how to integrate it inside TopFunction.
Thank you very much for your help and insights!
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
</style>
<button onclick="topFunction()" id="myBtn"></button>
<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
}
</script>
RANDOM POST
<script type="text/javascript">
function showLucky(root){ var feed = root.feed; var entries = feed.entry || []; var entry = feed.entry[0]; for (var j = 0; j < entry.link.length; ++j){if (entry.link[j].rel == 'alternate'){window.location = entry.link[j].href;}}} function fetchLuck(luck){ script = document.createElement('script'); script.src = '/feeds/posts/summary?start-index='+luck+'&max-results=1&alt=json-in-script&callback=showLucky'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); } function feelingLucky(root){ var feed = root.feed; var total = parseInt(feed.openSearch$totalResults.$t,10); var luckyNumber = Math.floor(Math.random()*total);luckyNumber++; a = document.createElement('a'); a.href = '#random'; a.rel = luckyNumber; a.onclick = function(){fetchLuck(this.rel);}; a.innerHTML = 'RANDOM POST'; document.getElementById('myBtn').appendChild(a); } </script><script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
I have no idea if below is correct or not. In order to help you correctly we need to know WHERE the codes are coming from. And you need to explain into detail what you have tried.
Below might work: I have added a <div> for which should contain the random posts when button is clicked. Content can be styled as you wish.
Be aware of the path /feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky. This is hardcoded and the JS script change some word in it. This needs to be the same (and the one in the code) to your own folderstructure.
I have also cleared up your code a little... Always use id for scripts and class for CSS styling.
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
//Why is this empty?
};
function showLucky(root) {
var feed = root.feed;
var entries = feed.entry || [];
var entry = feed.entry[0];
for (var j = 0; j < entry.link.length; ++j) {
if (entry.link[j].rel == 'alternate') {
window.location = entry.link[j].href;
}
}
};
function fetchLuck(luck) {
script = document.createElement('script');
script.src = '/feeds/posts/summary?start-index=' + luck + '&max-results=1&alt=json-in-script&callback=showLucky';
script.type = 'text/javascript';
document.getElementsByTagName('randompost')[0].appendChild(script);
}
function feelingLucky(root) {
var feed = root.feed;
var total = parseInt(feed.openSearch$totalResults.$t, 10);
var luckyNumber = Math.floor(Math.random() * total);
luckyNumber++;
a = document.createElement('a');
a.href = '#random';
a.rel = luckyNumber;
a.onclick = function() {
fetchLuck(this.rel);
};
a.innerHTML = 'RANDOM POST';
document.getElementById('myBtn').appendChild(a);
};
.myBtn {
display: block;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
.myBtn:hover {
background-color: #555;
}
.myDiv {
width: 50%;
height: auto;
background: rgba(255,0,0,0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="showLucky()" id="myBtn" class="myBtn">Try me</button>
<div class="myDiv" id="randompost" >
<script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
Something here...
</div>
Related
I've a table inside a div inside the main.
all of this have width = 100% but when i make the window smaller just the div ant the main gets smaller but the table dosent resize. all other elements below the table change position and size and starts lay over it. the table has 25 records and if the window is full-size everything matches perfect.
The div im talkin about has the id home
The html:
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin Panel | Please Login</title>
<link href='../css/admin.css' type='text/css' rel='stylesheet'>
<meta http-equiv="refresh" content="60">
</head>
<body>
<main>
<div id='container'>
<img src="../img/ipw_quer_rgb.jpg" alt="IPW Logo" id="logo" width="15%">
<header>
<ul id='menu'>
<div id="links">
<li>Home</li>
<li>Schüler verwalten</li>
<li>History</li>
</div>
</ul>
</header>
<div id="home">
<h2 id="date"></h2>
<table id="table">
</table>
</div>
<div id="dropdown" class="dropdown">
<select id="select">
<option value="Nothing">Nichts ausgewählt</option>
<option value="Extern">Extern</option>
<option value="Termin">Termin</option>
<option value="Schule">Schule</option>
</select>
</div>
<div id="legend" class="legend">
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#D3D3D3;" />
</svg>
<a>Extern</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFAEB9;" />
</svg>
<a>Termin</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFFF00;" />
</svg>
<a>Schule</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#00FF00;" />
</svg>
<a>Visiert</a>
<br>
<button id="edit">Editieren</button>
</div>
</div>
</main>
the css:
*{
margin: 0;
padding: 0;
font-family: monospace;
box-sizing: border-box;
}
main{
height: 100%;
width: 100%;
}
label{
font: 13px Helvetica, Arial, sans-serif;
}
html, body{
background-color: #006975;
overflow-y:auto;
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
h3{
margin-right:50%;
}
table{
width:100%;
height:calc(100% -50px);
}
ul {
width:100%;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #006975;
}
li {
width:25%;
float: left;
}
h1{
text-align:center;
}
li a {
display: block;
color: white;
font-size: 120%;
text-align: center;
padding: 14px 16px;
border-left: 2px solid #fff;
border-right: 2px solid #fff;
text-decoration: none;
}
/* Change the link color to #111 (black) on hover */
li a:hover {
color: #006975;
background-color: #fff;
}
button:hover{
color:#fff;
background-color:#84afb8;
}
#container{
position:absolute;
margin: 4% 4% 4% 4%;
padding: 2%;
width: 90%;
height: 90%;
background-color: #fff;
}
#home{
height:60%;
}
#dropdown{
width:100%;
height:2%;
visibility:hidden;
}
.cell {
height: 4%;
width:10%;
text-align: center;
background-color: #D3D3D3;
}
.cell.on {
height: 4%;
width: 10%;
background-color: #00FF00;
}
.cell.les {
height: 4%;
width: 10%;
background-color: #FFFF00;
}
.cell.term {
height: 4%;
width: 10%;
background-color: #FFAEB9;
}
.cell.ext{
height: 4%;
width: 10%;
background-color: #D3D3D3;
}
.cell.spacer {
height: 4%;
width: 10%;
background-color:white;
}
.name {
border: 1px solid black;
}
if you also need the javascript please ask
EDIT:
javascript:
getDataUser('logGLAUSB');
var names = ["Zebra","Benj", "Nico", "Timon","Miro", "Leo"];
var longpresstimer = null;
getData();
window.addEventListener('click', function(){
});
window.addEventListener('load', function () {
var clickcount = 0;
var singleClickTimer;
document.getElementById('table').addEventListener('click', function (event) {
clickcount++;
if(clickcount==1){
if(event.target.tagName != "INPUT" && event.target.classList != 'cell spacer'){
singleClickTimer = setTimeout(function() {
clickcount = 0;
var cell = event.target;
var selected = getSelected();
if(selected == 3){
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.add("on");
}else{
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.remove("on");
switch(selected){
case 0: cell.classList.add("ext"); break;
case 1: cell.classList.add("les"); break;
case 2: cell.classList.add("term"); break;
}
}
var x = "get";
x += getString(event.target.parentNode.cells[0].childNodes[0].innerHTML);
getData(x);
}, 300);
}
}else if (clickcount == 2){
if(event.target.classList != "name"){
clearTimeout(singleClickTimer);
clickcount = 0;
toInput(event.target);
}
}
});
});
document.getElementById("edit").addEventListener('click', function(){
var legend = document.getElementById("legend");
var dropdown = document.getElementById('dropdown');
var select = document.getElementById('select');
legend.style.visibility = 'hidden';
dropdown.style.visibility = 'visible';
var button = document.createElement('button');
button.innerHTML= "Fertig";
dropdown.appendChild(button);
button.onclick = function(){
legend.style.visibility = 'visible';
dropdown.style.visibility = 'hidden';
dropdown.removeChild(button);
select.value = "Nothing";
}
});
function reset(){
var rows = Array.from(document.getElementsByClassName('row'));
var table = document.getElementById('table');
rows.forEach(function (row){
var cells = Array.from(document.getElementsByClassName('cell'));
for(var i = 0;i< cells.length;i++){
var cell = cells[i]
cell.classList.remove('on');
cell.classList.remove('les');
cell.classList.remove('term');
cell.classList.remove('ext');
}
});
var x = "rep";
x += getResetString();
getData(x);
}
function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
function getData(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/students.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
loadJson(request);
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataHistory(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/history.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
}
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataUser(str){
var requestURL = "http://adopraesenz.ipwin.ch/data/login.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
} }
};
request.open("GET", requestURL, true);
request.send();
}
function getSelected(cell) {
var value = document.getElementById("select").value;
switch(value){
case "Extern": return 0; break;
case "Schule": return 1; break;
case "Termin": return 2; break;
default: return 3;
}
}
function loadDate(request){
var newDate = new Date();
newDate.setDate(newDate.getDate() -1);
newDate.setHours(0,0,0,0);
var days = request.responseText.split(".");
var oldDate = new Date(days[1]+"."+days[0]+"."+days[2]);
if(newDate > oldDate){
var date = new Date();
date.setDate(date.getDate() - 1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
if(dd < 10) {
dd = '0' +dd;
}
if(mm < 10) {
mm = '0' +mm;
}
var yesterday = dd+"."+mm+"."+yyyy;
getDataHistory('add' + yesterday);
reset();
}
newDate = new Date().toLocaleDateString('de-CH', {
weekday: 'long',
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
document.getElementById('date').innerHTML = newDate;
}
getDataHistory('new');
function loadJson(request){
createTable(request.responseText);
}
function createHeader(array){
var header = document.createElement("thead");
var hRow = document.createElement('tr');
hRow.classList.add('header');
for(var i = 0; i < array.length; i++){
var div = document.createElement('div');
var th = document.createElement('th');
div.innerHTML = array[i];
th.appendChild(div);
hRow.appendChild(th);
}
header.appendChild(hRow);
return header;
}
function createTable(json){
var obj = JSON.parse(json);
var oldBody = document.getElementsByTagName('tbody')[0];
console.log(oldBody);
var oldHeader = document.getElementsByTagName('thead')[0];
var body = document.createElement('tbody');
var header = createHeader(["Name","09:00 – 09:45","10:15 – 11:00","11:00 – 11:45"," ","14:00 – 14:45","15:00 - 15:45","16:00 – 16:45"]);
for (var j = 0; j < obj.length; j++) {
var row = addRow(obj[j],body);
row.classList.add('row');
}
console.log(body);
replaceTable(body, oldBody, header ,oldHeader);
if(obj.length > 25){
var view = document.getElementById('home');
view.setAttribute("style", "overflow-y:scroll");
}
}
function toInput(cell){
var input = document.createElement('input');
setTimeout(function() { input.focus(); }, 200);
cell.appendChild(input);
window.addEventListener('keypress', function(e){
if(e.keyCode == '13'){
var text = input.value;
if(input.parentNode != null){
input.parentNode.removeChild(input);
}
cell.innerHTML = text;
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
}
}, false);
}
function replaceTable(body, oldBody, header, oldHeader){
if(typeof oldHeader == 'undefined'){
table.appendChild(header);
}else if(oldHeader.parentNode == table){
table.replaceChild(header, oldHeader);
}else{
table.appendChild(header);
}
if(typeof oldBody == 'undefined'){
table.appendChild(body);
}else if(oldBody.parentNode == table){
table.removeChild(oldBody);
table.appendChild(body);
//table.replaceChild(body, oldBody);
}else{
table.appendChild(body);
}
}
function addRow(val,body) {
var rest = val.split(";");
var tr = document.createElement('tr');
for( var i = 0; i < 8; i++){
if(i==0){
var name = rest[0];
addCell(tr, null,name);
}else{
var value = rest[i];
addCell(tr, value, name);
}
}
body.appendChild(tr);
return tr;
}
function addCell(tr, val, name) {
var name;
var cell = document.createElement('td');
var value = "get";
if(val == null){
var input = document.createElement('label');
cell.classList.add("name")
input.innerHTML = name;
input.readOnly = true;
cell.appendChild(input);
}else{
cell = document.createElement('td');
cell.classList.add('cell');
var content = val.split(":");
switch(content[0]){
case '0': cell.classList.add('ext'); break;
case '1': cell.classList.add('les'); break;
case '2': cell.classList.add('term'); break;
case '3': cell.classList.add('on'); break;
case '4': cell.classList.add('spacer'); break;
}
if(val.length > 1){
cell.innerHTML = content[1];
}
}
tr.appendChild(cell);
}
window.onclick = function(event) {
if (!event.target.matches('.dropA')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
function getString(name){
var x = "";
var names = document.getElementsByClassName('name');
var values = document.getElementsByClassName('cell');
for(var i = 0;i<names.length;i++){
if(names[i].childNodes[0].innerHTML == name){
x+= names[i].childNodes[0].innerHTML + ";";
for(var j = (7 * i); j < (7 * i) + 7 ; j++){
switch(""+values[j].classList){
case 'cell': x += "0"; break;
case 'cell ext': x += "0"; break;
case 'cell les': x += "1"; break;
case 'cell term': x += "2"; break;
case 'cell on': x += "3"; break;
case 'cell spacer': x += "4"; break;
}
if(values[j].innerHTML != "" && values[j].innerHTML != null){
x+= ":" + values[j].innerHTML
}
x += ";";
}
}
}
return x;
}
function getResetString(){
var names = document.getElementsByClassName('name');
var x = "";
for(var i = 0; i < names.length; i++){
x += names[i].value +";";
for (var j = 0; j < 7 ; j++){
if(j == 3){
x += "4";
}else{
x += "0";
}
x += ";";
}
if(i < names.length-1){
x+="|";
}
}
return x;
}
it seems a tiny problem. on your css, you have to add an space on the calc statement:
height:calc(100% - 50px);
I was able to make it work in here
https://codesandbox.io/s/vibrant-http-ty85k
You can add display: table; to #container
and add:
#legend {
display: table-row;
}
This should work, but I think you should refactor (simplify) the whole page and styles.
Hi I wanted to know if its possible to create a button in html that functions like a "Browse" button like when clicked it will show the computer directory such as the Local Drive, Documents etc.
What I wanted to do is use this "Browse" button to set a Folder path that has Images (.png/.jpeg) then once directory folder has been selected the image file name should show up in a list form.
*Note: The machine is connected on a LAN network everything is shared and with
out any restriction.
Sample
Path:
C:\Documents\TargetFolder (this is what will be browsed using the "Browse" button the path location may change could be from a different location within the same machine or different computer over the same network that is why a "Browse" button is needed)
Output:
From the Source(TargetFolder) lets say with 20 image file a list should show up with the image file name, path properties(created date and time )and the actual image pulled up. Switches as well base on what was selected on the list
Is this possible?
browse button window
webpage looks like this
What you want actually is a file manager (file gallery to be more precise) in web browser.
there is no such thing in that would help you get that without writing hundreds of lines of code.
This link might help you https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
and also follow the below code
var input = document.querySelector('input');
var preview = document.querySelector('.preview');
input.style.opacity = 0;input.addEventListener('change', updateImageDisplay);function updateImageDisplay() {
while(preview.firstChild) {
preview.removeChild(preview.firstChild);
}
var curFiles = input.files;
if(curFiles.length === 0) {
var para = document.createElement('p');
para.textContent = 'No files currently selected for upload';
preview.appendChild(para);
} else {
var list = document.createElement('ol');
preview.appendChild(list);
for(var i = 0; i < curFiles.length; i++) {
var listItem = document.createElement('li');
var para = document.createElement('p');
if(validFileType(curFiles[i])) {
para.textContent = 'File name ' + curFiles[i].name + ', file size ' + returnFileSize(curFiles[i].size) + '.';
var image = document.createElement('img');
image.src = window.URL.createObjectURL(curFiles[i]);
listItem.appendChild(image);
listItem.appendChild(para);
} else {
para.textContent = 'File name ' + curFiles[i].name + ': Not a valid file type. Update your selection.';
listItem.appendChild(para);
}
list.appendChild(listItem);
}
}
}var fileTypes = [
'image/jpeg',
'image/pjpeg',
'image/png'
]
function validFileType(file) {
for(var i = 0; i < fileTypes.length; i++) {
if(file.type === fileTypes[i]) {
return true;
}
}
return false;
}function returnFileSize(number) {
if(number < 1024) {
return number + 'bytes';
} else if(number >= 1024 && number < 1048576) {
return (number/1024).toFixed(1) + 'KB';
} else if(number >= 1048576) {
return (number/1048576).toFixed(1) + 'MB';
}
}
html {
font-family: sans-serif;
}
form {
width: 600px;
background: #ccc;
margin: 0 auto;
padding: 20px;
border: 1px solid black;
}
form ol {
padding-left: 0;
}
form li, div > p {
background: #eee;
display: flex;
justify-content: space-between;
margin-bottom: 10px;
list-style-type: none;
border: 1px solid black;
}
form img {
height: 64px;
order: 1;
}
form p {
line-height: 32px;
padding-left: 10px;
}
form label, form button {
background-color: #7F9CCB;
padding: 5px 10px;
border-radius: 5px;
border: 1px ridge black;
font-size: 0.8rem;
height: auto;
}
form label:hover, form button:hover {
background-color: #2D5BA3;
color: white;
}
form label:active, form button:active {
background-color: #0D3F8F;
color: white;
}
<form method="post" enctype="multipart/form-data">
<div>
<label for="image_uploads">Choose images to upload (PNG, JPG)</label>
<input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple>
</div>
<div class="preview">
<p>No files currently selected for upload</p>
</div>
<div>
<button>Submit</button>
</div>
</form>
Not exactly what you asked for, but (if it works for your use-case), the user could select multiple files from the same directory using the browse button.
There is a lovely example on MDN
https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications#example_showing_thumbnails_of_user-selected_images
<input type="file" id="input" multiple>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
}
function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith('image/')){ continue }
const img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.
const reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
This code section performs a simple test for left or right swipe and then produces an alert saying which has been detected. It works fine in Chrome but fails in IE11. I suspect the fault lies in the addEventListener elements of the function swipedir but I cannot figure out what IE is objecting to or ignoring. Any help will be gratefully received. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<style>
#touchsurface{
width: 1240px;
height: 1400px;
padding: 10px;
font-size: 24px;
line-height: 1.1em;
background: lightyellow;
border: 1px solid orange;
}
#touchsurface2{
width: 1280px;
height: 1400px;
border: 1px solid orange;
background: lightyellow top center no-repeat;
}
#touchsurface2 #inner{
width: 100%;
height: 100%;
}
</style>
<script>
function swipedetect(el, callback){
var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 150,
restraint = 100,
allowedTime = 300,
elapsedTime,
startTime,
handleswipe = callback || function(swipedir){}
touchsurface.addEventListener("touchstart", function(e){
var touchobj = e.changedTouches[0];
swipedir = "none";
dist = 0;
startX = touchobj.pageX;
startY = touchobj.pageY;
startTime = new Date().getTime() ;
e.preventDefault();
}, false);
touchsurface.addEventListener("touchmove", function(e){
e.preventDefault() ;
}, false);
touchsurface.addEventListener("touchend", function(e){
var touchobj = e.changedTouches[0];
distX = touchobj.pageX - startX ;
distY = touchobj.pageY - startY ;
elapsedTime = new Date().getTime() - startTime ;
if (elapsedTime <= allowedTime){
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
swipedir = (distX < 0)? "left" : "right" ;
}
}
if (distX > 0) {swipedir = "right";}
if (distX < -1) {swipedir = "left";}
handleswipe(swipedir);
e.preventDefault();
}, false);
}
</script>
</head>
<body>
<script>
window.addEventListener("load", function(){
var el = document.getElementById("touchsurface2");
var inner = document.getElementById("inner");
var hidetimer = null;
swipedetect(el, function(swipedir){
if (swipedir != "none"){
alert(swipedir);
clearTimeout(hidetimer);
hidetimer = setTimeout(function(){
inner.style.background = '';
}, 1000)
}
});
}, false);
</script>
<div id="touchsurface2">
<div id="inner">
Swipe Me
</div>
</div>
</body>
</html>
I'm creating a sort of slider which when a certain point on the window is clicked the element will stretch its width to that point. I would also like to add a drag event handler and I have read about mousedown and mousemove and mouseup being the three handlers that need to be combined. This code works quite well but I'm wondering is there a better way to combine these handlers because at the moment I am repeating code whihc Im not sure is necessary. I'm quite new to javascript and jquery. Thanks for the help
function reposition_bar(mouse_touch_position){
document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
and here is where i create the event listener.
$(timer_area).on("mousedown", reposition_bar);
my html:
<div id="timer_area0" class="timer_area">
<div id="timer_bar_outer0" class="timer_bar_outer"></div>
<div id="timer_bar0" class="timer_bar"></div>
</div>
and my css:
.timer_area{
position: relative;
width: 100%;
margin: 20px auto 10px auto;
height: 20px;
backgroud: #fff;
}
.timer_bar{
z-index: -1;
display: block;
width: 3%;
height: 8px;
border-radius: 4px;
clear: both;
position: absolute;
margin-top: 6px;
box-shadow: inset 0px 1px 0px 0px rgba(250,250,250,0.5),
0px 0px 3px 2px rgba(250,250,250,1);
background-color: #fff;
}
.timer_bar_outer{
padding: 0px 3% 0px 3%;
width: 100%; /*this should be same number as 100/windowduration*/
height: 20px;
display: block;
z-index: -2;
position: absolute;
background-color: rgb(0,0,0);
margin-left: -3%;
border-radius: 10px;
box-shadow: 0px 1px 0px 0px rgba(250,250,250,0.1),
inset 0px 1px 2px rgba(0, 0, 0, 0.5);
box-sizing: content-box;
}
.timer_bar.on{
background-color: blue;
box-shadow: inset 0px 1px 0px 0px rgba(250,250,250,0.5),
0px 0px 3px 2px rgba(5,242,255,1);
}
Edit after #tlindell comment:
thank you for your comment. I have tried out the range sliders but could not style them with css the way i wanted after doing much research. (ie my vertical slider worked perfect until I put a box shadow on it and it did not work vertically anymore)... I am happy with my slider. its just i was wondering if i could have written the reposition_bar method better because the way ive done it above, this code:
document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
is exaclty the same as this accept they are different event handlers e.g onmousemove and onclick:
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
so can i combine them in a way for example
document.onmousemove || document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
Thanks for your edit #tlindell. It is something like what I would like but I tried the following which doesnt really have the desired effect. It is not registering the mouseup event.
function reposition_bar(mouse_touch_position){
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
$(timer_area).on("mousedown click", reposition_bar);
I would like the function to be called with onmousedown and then within the function I would like it to handle the events of onmousemove and onclick. can I do something like this within the function reposition_bar:
function reposition_bar(mouse_touch_position){
document.on("mousemove click") = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
$(timer_area).on("mousedown", reposition_bar);
That does not work at all though so I guess the syntax is wrong in this line within the function:
document.on("mousemove click") = function(mouse_touch_position){
}
Thanks again. I am quite new to this :)
Thanks #tlindell for the answer.
This is what i did in the end. (see the window.onload section for the edits)
<script>
var player;
var intv;
var duration;
var song_id;
var button;
//init
window.onload = function(){
player = document.getElementById('audio_player');
$('#volume_control_area').on('mousedown mouseup mouseleave click', function(e){
if(e.type === 'mousedown'){
$(this).bind('mousemove', reposition);
}
else if((e.type === 'mouseup') || (e.type === 'mouseleave')) {
$(this).unbind('mousemove', reposition);
}else if(e.type === 'click'){
$(this).bind('click', reposition);
}
});
}
function reposition(mouse_volume_position){
var volume_knob_position = $(".volume_control_knob");
volume_area_offset = $('#volume_control_area').offset();
var total_height_volume = $('#volume_control_area').height();
console.log(total_height_volume);
var new_height_volume = ((volume_area_offset.top + total_height_volume)- mouse_volume_position.pageY); /*converting to percantages because the width of the timer is in percentages in css*/
if(new_height_volume > 8 && new_height_volume <= 100){
console.log(new_height_volume);
player.volume = new_height_volume/100;
$(".volume_control_knob").css({
'height' : new_height_volume + '%'
});
}
}
</script>
Welcome Jquery ui!
you can resize divs here:
jquery ui resizable
and get range sliders here:
Jquery ui silders
EDIT
absolutely! here is the way to do that.
$('#element').on('keyup keypress blur change', function() {
...
});
Or just pass the function as the parameter to normal event functions:
var myFunction = function() {
...
}
$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)
.change(myFunction)
jQuery multiple events to trigger the same function
UPDATE:
<script>
let player;
let intv;
let duration;
let song_id;
let button;
//init
window.onload = function(){
player = document.getElementById('audio_player');
$('#volume_control_area').on('mousedown mouseup', function(e){
if(e.type === 'mousedown'){
$(this).bind('mousemove', reposition);
}
else if(e.type === 'mouseup'){
$(this).unbind('mousemove', reposition);
}
})
}
function reposition(mouse_volume_position){
let volume_knob_position = $(".volume_control_knob");
let volume_area_offset = $('#volume_control_area').offset();
let total_height_volume = $(volume_control_area).height();
let new_height_volume = ((volume_area_offset.top + total_height_volume)- mouse_volume_position.pageY); /*converting to percantages because the width of the timer is in percentages in css*/
if(new_height_volume > 8 && new_height_volume <= 100){
console.log(new_height_volume);
player.volume = new_height_volume/100;
$(".volume_control_knob").css({
'height' : new_height_volume + '%'
});
}
}
</script>
Below code is working for excel to html conversion and partial sorting.
I want when any cells in the header(or first row) is clicked the entire table should get sorted
based on that column(either ascending or descending).
Note:Below Code is tested with any excel input file and supporting settings for activex in internet options in IE9.
<HTML>
<HEAD>
<TITLE>Test</TITLE> <script type="text/javascript" src="../jquery-latest.js"></script>
<script type="text/javascript">
</script>
<STYLE TYPE="text/css">body div * { font-family: Verdana; font-weight: normal; font-size: 10px; } body { background-color: #FFEEFF; } .tableContainer table { border: 0px solid #000000; } .tblHeader { font-weight: bold; text-align: center; background-color: #FFAAEE; color: black; } .oddRow, .evenRow { vertical-align: top; } .tblHeader td, .oddRow td, .evenRow td { border-left: 2px solid #FFFFFF; border-bottom: 0px solid #000000; border-top: 0px solid #000000;} .lastCol { border-right: 0px solid #000000; } .oddRow { background-color: #abcdef; } .evenRow { background-color: #f0f0f0; }</STYLE>
<script LANGUAGE="JavaScript">
function _ge(id) {
return document.getElementById(id);
}
function sortTable(){
var tbl = document.getElementById("tblExcel2Html").tBodies[0];
var store = [];
//alert(tbl.rows.length);
for(var i=0, len=tbl.rows.length; i<len; i++){
var row = tbl.rows[i];
//alert(row.cells[1].innerText);
var sortnr = parseFloat(row.cells[1].textContent || row.cells[1].innerText);
if(!isNaN(sortnr)){
alert(store.push([sortnr, row]));
//store.push([sortnr, row]);
}
}
store.sort(function(x,y){
//alert(x[0] - y[0]);
return x[0] - y[0];
});
//alert(store.length);
for(var i=0, len=store.length; i<len; i++){
alert(tbl.appendChild(store[i][1]));
//alert(tbl.appendChild(store[i][1]));
}
//alert(store);
store = null;
}
function convert2HTML() {
var ex;
try {
ex = new ActiveXObject("Excel.Application");
}
catch (e)
{
alert('Your browser does not support the Activex object.\nPlease switch to Internet Explorer.');
return false;
}
//alert(arraytext);
//var ef = ex.Workbooks.Open("D:\\JS_HTML5\\Vin\\Test.xlsx");
var ef = ex.Workbooks.Open("D:\\JS_HTML5\\docs\\filter4\\tests\\Test.xlsx");
var es = ef.Worksheets(1);
var colsCount = ef.Worksheets(1).UsedRange.Columns.Count;
//alert(colsCount);
var rowsCount = ef.Worksheets(1).UsedRange.Rows.Count;
//alert(rowsCount);
var rStart = parseInt(1,10);
var cStart = parseInt(1,10);
var cEnd = parseInt(colsCount,10);
var rEnd = parseInt(rowsCount,10);
var oc = _ge('tableContainer');
oc.innerHTML = '';
var tbl = document.createElement('TABLE');
tbl.id = 'tblExcel2Html';
tbl.border = '10';
tbl.cellPadding = '4';
tbl.cellSpacing = '0';
oc.appendChild(tbl);
var i,j,row,col,r,c;
for(i = rStart, r = 0; i <= rEnd; i++,r++) {
row = tbl.insertRow(r);
row.className = (i == rStart) ? 'tblHeader' : (i % 2 == 0) ? 'evenRow' : 'oddRow';
for(j = cStart, c = 0; j <= cEnd; j++,c++) {
col = row.insertCell(c);
col.className = (j == cEnd) ? 'lastCol' : '';
col.innerHTML = es.Cells(i,j).value || ' ';
}
}
ex.ActiveWorkbook.Close(true);
ex.Application.Quit();
ex = null;
sortTable();
}
</script>
</HEAD>
<BODY onload = "convert2HTML()">
<h2>Test</h2>
<hr><br>
<!-- <td colspan="6" align="CENTER"><INPUT TYPE="button" VALUE="Convert to HTML" ONCLICK="convert2HTML()"></td> -->
<div id="tableContainer"></div>
<div id="tblExcel2Html"></div>
<footer>
<br>
<center> ©Initial Draft V0.1 </center>
</footer>
<a href="Home.html" >Home</a>
</BODY>
Basically i want to convert excel to html with sorting and filtering support.
Thanks in Advance
Vinoth.S
The creation of the object by calling
ex = new ActiveXObject("Excel.Application");
works only in windows systems with Excel installed. I suggest you to use jqgrid as javascript data-viewer and a php library like phpexcel that parse the excel and return raw data.