HTML/CSS - Using a image for input type=file - html

How do use this image:
http://h899310.devhost.se/proxy/newProxy/uplfile.png
Instead of the regular:
<input type="file" />

Have a look at Styling an input type="file".

I'm not very sure on whether you want to style file upload fields, or whether you simply want to use a png file in a style.
Quirksmode.org has a section on styling file upload fields though, that you would want to refer to.
If you want to use the PNG file to use in a style inside a page, you should like at how to set backgrounds using images, although this may not work for all HTML elements.

I did something like this and it worked perfectly!
<script type="text/javascript">
var t = 0;
var IE = navigator.appName;
var OP = navigator.userAgent.indexOf('Opera');
var tmp = '';
function operaFix() {
if (OP != -1) {
document.getElementById('browser').style.left = -120 + 'px';
}
}
function startBrowse() {
tmp = document.getElementById('dummy_path').value;
getFile();
}
function getFile() {
// IF Netscape or Opera is used...
//////////////////////////////////////////////////////////////////////////////////////////////
if (OP != -1) {
displayPath();
if (tmp != document.getElementById('dummy_path').value && document.getElementById('dummy_path').value
!= '') {
clearTimeout(0);
return;
}
setTimeout("getFile()", 20);
// If IE is used...
//////////////////////////////////////////////////////////////////////////////////////////////
} else if (IE == "Microsoft Internet Explorer") {
if (t == 3) {
displayPath();
clearTimeout(0);
t = 0;
return;
}
t++;
setTimeout("getFile()", 20);
// Or if some other, better browser is used... like Firefox for example :)
//////////////////////////////////////////////////////////////////////////////////////////////
} else {
displayPath();
}
}
function displayPath() {
document.getElementById('dummy_path').value = document.getElementById('browser').value;
}
</script>
<style type="text/css">
#browser
{
position: absolute;
left: -132px;
opacity: 0;
filter: alpha(opacity=0);
}
#browser_box
{
width: 104px;
height: 22px;
position: relative;
overflow: hidden;
background: url(button1_off.jpg) no-repeat;
}
#browser_box:active
{
background: url(button1_on.jpg) no-repeat;
}
#dummy_path
{
width: 350px;
font-family: verdana;
font-size: 10px;
font-style: italic;
color: #3a3c48;
border: 1px solid #3a3c48;
padding-left: 2px;
background: #dcdce0;
}
</style>
<body onload="operaFix()">
<div id="browser_box">
<input type="file" name="my_file" id="browser" onclick="startBrowse()" />
</div>
</body>

Related

How to give some space between my buttons

I need help giving my buttons some space. No matter what I try, I just can't seem to space them out.
You can see my github repository here.
The following is my HTML with stylesheets inside.
<script src="update.js"></script>
<script src="sw.js"></script>
<script>
let d = new Date();
//alert(d);
let hrs = d.getHours();
let min = d.getMinutes();
let day = d.getDay();
let auth = false;
fetch('https://raw.githubusercontent.com/AzlanCoding/iframe-browser-pwa/main/lock.js')
.then(response => response.text())
.then(data => {
let split_str = "/split/";
const data_arr = data.split(split_str);
let lock = data_arr[1];
if (data_arr[0] === "lock") {
setInterval(lock,500);
}else{
alert(data_arr[0]);
}
console.log(data_arr[0]);
});
</script>
<!DOCTYPE html>
<html lang="en">
<style>
body {
background-color: ##2C2F33;
}
</style>
<head>
<meta name="theme-color" content="#2C2F33">
<meta charset="UTF-8">
<meta name="description" content="Azlan's iframe Browser">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0, no-store">
<!meta http-equiv="cache-control" content="max-age=0" />
<!meta http-equiv="Pragma" content="no-cache">
<!meta http-equiv="Expires" content="0">
<title> Iframe Browser </title>
<link rel="canonical" href="https://azlancoding.github.io/iframe-browser-pwa/" />
<link rel="manifest" href="/iframe-browser-pwa/manifest.webmanifest">
<meta name="keywords" content="bypass, school, browser in website, cloud browser">
<link rel="stylesheet" href="css/styles.css">
<title> iFrame browser </title>
<script language="javascript">
const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `https${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `https://${newUrl}`;
}
return newUrl;
};
function setCookie(c_name,value,exdays){
var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}
else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1){
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
checkSession();
function checkSession(){
var c = getCookie("visited");
if (c === "yes") {
alert("Welcome back! Make sure you have your extension on.");
}
else {
alert("By continuing, you agree to the terms and conditions in azlancoding.github.io/iframe-browser/TermsAndConditions")
ext_install();
}
}
function ext_install()
{
if (window.confirm('An extension is required for this website to work. Do you want to install it now?'))
{
setCookie("visited", "yes", 365)
window.location.href='https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe';
};
};
function checkCookie() {
let user = getCookie("alerted");
if (user != "") {
alert("Welcome again !");
} else
{ext_install();}
}
//document.getElementById("myIframe").src = "https://wwf.org";
var iframe = document.getElementById("myIframe");
//var website = iframe.src;
//console.log(website);
document.addEventListener("scroll", function(event)
{
var style = document.getElementById("myIframe").style;
style.webkitTransform = style.webkitTransform ? "" : "scale(1)";
})
/*function resizeIframe()
{
document.getElementById('myIframe').height = 100%;
}*/
function ResetBox()
{
if(document.getElementById("URL").value == '')
{document.getElementById("URL").value='';};
}
function LoadPage()
{
var objFrame=document.getElementById("myIframe");
var newurl = getValidUrl(document.getElementById("URL").value);
objFrame.src = newurl;
}
var elem = document.documentElement
function openFullscreen() {
if (elem.requestFullscreen)
{
elem.requestFullscreen();
}
else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
}
function closeFullscreen() {
if (document.exitFullscreen)
{
document.exitFullscreen();
}
else if (document.webkitExitFullscreen)
{
document.webkitExitFullscreen();
}
else if (document.msExitFullscreen)
{
document.msExitFullscreen();
}
}
</script>
<style>
.iframe-container {
overflow: visible;
/* 16:9 aspect ratio */
//padding-top: 56.25%;
position: 60px 0px;
//margin-top: 60px;
}
:root {
--fallback-title-bar-height: 45px;
}
.draggable {
app-region: drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: drag;
}
.nonDraggable {
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
#child {
width: window.innerWidth;
//height: window.innerHeight;
height: 100vh;
flex: 1 1 auto;
position: absolute;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
left: 0;
right: 0;
}
.button {
background-color: #ffffff;
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 10px;
margin: 4px 2px;
margin-right: 5px;
cursor: pointer;
border-radius: 10px;
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
fieldset {
border: 0px;
}
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
}
#titleBarContainer {
position: absolute;
top: 0;
left: 0;
height: env(titlebar-area-height, var(--fallback-title-bar-height));
width: 100%;
background-color:#254B85;
}
#titleBar {
position: absolute;
top: 0;
display: flex;
user-select: none;
height: 100%;
left: env(titlebar-area-x, 0);
//left : 0px;
width: env(titlebar-area-width, 50%);
color: #FFFFFF;
font-weight: bold;
text-align: center;
}
#titleBar > span {
margin: 5;
padding: 0px 32px 0px 32px;
}
#titleBar > input {
flex: 1;
margin: 0px;
border-radius: 5px;
border: none;
padding: 8px;
}
#mainContent {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
overflow-y: scroll;
}
</style>
</head>
<body style="background-color:#254B85">
<div id="titleBarContainer" >
<div id="titleBar">
<span class="draggable">Iframe Browser</span>
<input class="nonDraggable" type="text" ID="URL" placeholder="Enter a URL" value="https://www.google.com"></input>
<input type="submit" class="frmSubmit" value="Go" onclick="LoadPage()">
<input type="button" VALUE="&#65513" onClick="history.back()">
<input type="button" VALUE="&#65515" onClick="history.forward()">
<input type="button" class="fullscreen" value="⛶" onclick="openFullscreen()">
<input type="button" class="Exitfullscreen" value="Exit Fullscreen" onclick="closeFullscreen()">
<input type="button" class="newWindow" value="New Window" onclick=" window.open('https://azlancoding.github.io/iframe-browser-pwa/','_blank')">
<input type="button" class="cloudbrowser" value="Cloud Browser" onclick="window.open('https://replit.com/#azlancoding/free-and-unlimited-cloud-browser?embed=true','_blank')">
</div>
</div>
<!div style="Clear:both;">
<!input type="text" value="https://www.google.com" class="frmUrlVal" ID="URL" placeholder = "Enter a URL" >
<!/div>
<div id = "child" >
<iframe align="top" width="100%" height="100%" allowtransparency="true" style="background: #FFFFFF;" src="https://www.google.com" onload = "check()" onerror"ext_install()" allow="camera;microphone" frameborder=yes loading ="lazy" name="myIframe" id="myIframe"> </iframe>
</div>
<script>
window.onbeforeunload = () => '';
var urlbox = document.getElementById("URL");
urlbox.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
LoadPage();
}
});
function check(){
document.getElementById("URL").value = "";
}
</script>
<script>
if (navigator.serviceWorker) {
navigator.serviceWorker.register (
'/iframe-browser-pwa/sw.js',
{scope: '/iframe-browser-pwa/'}
)
}
</script>
<script src="js/app.js"></script>
</body>
</html>
The stylesheet may be weird as it is used to support Windows Overlay Controls which allowed buttons to be placed on top next to the buttons to minimise, maximise and close the window. I just changed the manifest to support tabbed experimental feature.
Any help is appreciated.
Update:
I tried to use <span> but it over did it...

How to Search text from input field to textarea, and How to marked matched result Using Jquery?

I am trying to create simple jquery App, but i ran over small problem, which i can't solve, I want to search in textarea box form input field, if input form value will match textarea value, i want to marked matched text, picture below shows what i want to done, any suggestion?
$('#search').on('input', function(e) {
e.preventDefault();
var searchTxtBox = $('#search');
searchTxtBox.val(searchTxtBox.val().replace(/(\s+)/, "(<[^> ]+>)*$1(<[^> ]+>)*"));
var textarea = $('#editor');
var enew = '';
if (searchTxtBox.val() != '') {
enew = textarea.html().replace(/(<mark>|<\/mark> )/igm, "");
textarea.html(enew);
var query = new RegExp("(" + searchTxtBox.val() + ")", "gim");
newtext = textarea.html().replace(query, "<mark>$1</mark>");
newtext = newtext.replace(/(<mark>[^<>]*)((<[^> ]+>)+)([^<>]*<\/mark>)/, "</mark><mark>");
textarea.html(newtext);
} else {
enew = textarea.html().replace(/(<mark>|<\/mark> )/igm, " ");
textarea.html(enew);
}
});
mark {
background-color: red;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder='search' id='search'>
<div id="editor" rows="4" cols="50">
</div>
The simplest way I can think of is positioning a transparent element behind the textarea
and adding the results there:
Key features to program this:
The elements must render the same (size, font, line ect..)
The textarea must have a transparent background.
Whenever the textarea is changed (resized) we need to match the size of the result container.
Here is my implementation:
$(function(){
//Simple helper function to match the size of the elements:
function matchSize($base, $target) {
$target.css({
width : $base.outerWidth(),
height : $base.outerHeight()
});
}
//Attach whenever serach field changed run the query:
$("#search").keyup(function(){
let $search = $(this),
$input = $('#input');
let $result = $input.prev('code');
//Match size:
matchSize($input, $result)
//Search
let marked = $input.val().replace(
new RegExp("(" + $search.val().trim() + ")", "g"),
"<mark>$1</mark>"
);
//Set marked transparent text:
$result.html(marked);
});
//textarea can be resized so always match the size:
$('#input').bind('mouseup', function(){
let $input = $('#input');
let $result = $input.prev('code');
matchSize($input, $result)
});
});
.wrap {
position: relative;
display:block;
}
/* match the two */
.wrap code,
.wrap textarea {
position:absolute;
text-rendering: auto;
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
text-indent: 0px;
text-align: start;
appearance: textarea;
flex-direction: column;
white-space: pre-wrap;
overflow-wrap: break-word;
margin: 0em;
font: 400 13.3333px Arial;
border-width: 1px;
border-style: solid;
padding: 2px;
background-color:transparent;
z-index: 2;
box-sizing: border-box;
}
.wrap code {
z-index: 1;
top:0;
left:0;
border-color:transparent;
color:transparent;
background-color: white;
}
.wrap code mark {
color: transparent;
background-color: yellow;
padding:0;
margin:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<code></code>
<textarea id="input">the easiest way to do this and the quickest.</textarea>
</div>
<br/><br/><br/><br/>
Search: <input id="search" placeholder='Search' />

How to create a box around around controls in webprgramming

I have a few controls that I am attempting to encapsulate on my webpage. I have tried a few different methods on encapsulating my controls and they have not succeeded. I tried using a div and this did not work too well and I have also tried this post:
Create a group box around certain controls on a web form using CSS
What is happening is that a box is being created but it is at the top of my webpage instead of around the controls.
I would like to create a grey box similar to the ones found on this webpage:
https://img.labnol.org/di/trigger1.png
Below, I am attaching a copy of the CSS and HTML code that I am using in order to create my form. The form is a simple file upload form that I tweaked from an example. I am using this on my own, personal website.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
function changeText()
{
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:508px; margin-left: -4px; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Here is the CSS (which is referred to in the html as test.css):
body{
background: rgba(0,0,0,0.0);
}
form{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -250px;
width: 500px;
height: 200px;
border: 4px dashed #0D0D0D;
}
form p{
width: 100%;
height: 100%;
text-align: center;
line-height: 140px;
color: #0D0D0D;
font-family: Arial;
}
h2{
text-align: center;
}
form input[type="file"]{
position: absolute;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
outline: none;
opacity: 0;
}
form input[type="button"]{
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 508px;
height: 35px;
margin-top: -20px;
margin-left: -4px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover{
background: #149174;
color: #0C5645;
}
form input[type="button"]:active{
border:0;
}
form progressBar{
text-align: center;
}
Coming back to the HTML, the fieldset tags are placed around the controls that I am attempting to encapsulate. I left them there so that anyone can see the main issue that I am running into.
I apologize but I am very new to web programming. Any help will be greatly appreciated, thank you.
Note: how the box is created doesn't really matter to me. I would expect that the box is created in HTML and then I can style it using CSS.
The structure of your HTML is fine, but the position: absolute properties in your CSS are clashing with the fieldset.
Since <fieldset> is wrapping all your controls, I would suggeset giving it a fixed width and height and position your child elements based on that, i.e. use width: 100% for your children and give all of them the same margin so they align nicely. Also make sure you either edit your #progressBar style in the markup.
Here's a snippet with the changes I just mentioned:
body {
background: rgba(0, 0, 0, 0.0);
}
fieldset {
width: 508px;
height: 270px;
/* fixed width and height*/
margin: 13vh auto;
}
#p1 {
border: 4px dashed #0D0D0D;
/* modified the actual text box instead of the entire form */
width: 508px;
height: 140px;
line-height: 140px;
margin-top: 0px;
}
form p {
text-align: center;
color: #0D0D0D;
font-family: Arial;
}
h2 {
text-align: center;
}
form input[type="file"] {
position: absolute;
margin: 0;
outline: none;
width: 508px;
height: 140px;
margin: 22px 4px;
opacity: 1;
background-color: orange;
/* Last two properties are a visual representation. Delete background-color and set opacity to 0 */
}
form input[type="button"] {
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 100%;
/* width relative to parent fieldset */
height: 35px;
margin-top: -20px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover {
background: #149174;
color: #0C5645;
}
form input[type="button"]:active {
border: 0;
}
form progressBar {
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
function changeText() {
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<!-- changed progressBar style -->
<progress id="progressBar" value="0" max="100" style="width:100%; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Hope it helps!

Change Image on click HTML/CSS

I basically have two images (checkboxes), that when each one is clicked, it changes to a different image. However, it can only switch between two images only. I wanted to add a third one, how could I do that?
HTML:
<style>
body {
background-image: url("http://i.imgur.com/kcmsgdr.png");
background-color: #cccccc;
}
</style>
CSS:
#a{
margin: 3.55cm 5.025cm;
height: 40px;
width: 40px;
content: url(http://i.imgur.com/59fHyah.png);
}
#a:checked {
content: url(http://i.imgur.com/zgwd1n1.png);
}
#b{
margin: 3.55cm -0.65cm;
height: 40px;
width: 40px;
content: url(http://i.imgur.com/59fHyah.png);
}
#b:checked {
content: url(http://i.imgur.com/zgwd1n1.png);
}
#b{
margin: 3.55cm -0.65cm;
height: 40px;
width: 40px;
content: url(http://i.imgur.com/59fHyah.png);
}
#b:checked {
content: url(http://i.imgur.com/zgwd1n1.png);
}
Codepen: http://codepen.io/Coto16/pen/ENRdBv
with jquery its easy:
<html>
<input id="b" type="checkbox" onclick="changeImg()"/>
</html>
<style>
#b{
height: 40px;
width: 40px;
content: url(img1.png);
}
</style>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"> </script>
<script>
var changeImg = function(){
switch($("#b").css("content")){
case "url(img1.png)":
$("#b").css("content", "url(img2.png)");
break;
case "url(img2.png)":
$("#b").css("content", "url(img3.png)");
break;
case "url(img3.png)":
$("#b").css("content", "url(img1.png)");
break;
}
};
</script>
If you are not against JavaScript, you can use the following code:
var checkbox = document.getElementById('checkbox');
var checkbox_1 = document.getElementById('checkbox_1');
var checkbox_2 = document.getElementById('checkbox_2');
var img_1 = 'http://i.imgur.com/59fHyah.png';
var img_2 = 'http://i.imgur.com/zgwd1n1.png';
checkbox.onclick = function () {
if (checkbox.src == img_1) {
checkbox.src = img_2;
} else if (checkbox.src == img_2) {
checkbox.src = img_1;
}
}
checkbox_1.onclick = function () {
if (checkbox_1.src == img_1) {
checkbox_1.src = img_2;
} else if (checkbox_1.src == img_2) {
checkbox_1.src = img_1;
}
}
checkbox_2.onclick = function () {
if (checkbox_2.src == img_1) {
checkbox_2.src = img_2;
} else if (checkbox_2.src == img_2) {
checkbox_2.src = img_1;
}
}
<img src="http://i.imgur.com/59fHyah.png" id="checkbox" width="32"/>
<img src="http://i.imgur.com/59fHyah.png" id="checkbox_1" width="32"/>
<img src="http://i.imgur.com/59fHyah.png" id="checkbox_2" width="32"/>
Update
In your question, you'r using three buttons. So, I'm adding two more buttons to my code.

How can I make an Upvote/Downvote button?

I'm trying to make an upvote/downvote the same way that it's done on SO and Reddit, from what I can see they use arrow images as backgrounds and then position it, but I'm a CSS newbie and I need someone to walk me through it.
You could do it by adding a different picture to the background, one for every state of the button. There is however a cleaner, easier, more modern way of achieving this result: Sprites.
A sprite is an image that is saved as a part of a larger image. One of the biggest advantages of using sprites is the reduction of round-trips to the server for all the images to just one request for the Sprites. The element to display a picture has the image as background. The background is moved relative to the element so the element displays only part of the image. Like when you move a photo-frame over a poster (or in this case: moving the poster under the frame)
At SO they make an image that contains all the states for the button. They give the element for the button (a span in this case) a fixed width and height and add the background to it with CSS. Then toggle a class for the state (on or off) with javascript on the click event. Now the only thing you have to do in CSS is change the position of the background with CSS classes:
for (const btn of document.querySelectorAll('.vote')) {
btn.addEventListener('click', event => {
event.currentTarget.classList.toggle('on');
});
}
.vote {
display: inline-block;
overflow: hidden;
width: 40px;
height: 25px;
cursor: pointer;
background: url('http://i.stack.imgur.com/iqN2k.png');
background-position: 0 -25px;
}
.vote.on {
background-position: 0 2px;
}
Click to vote (using sprites): <span class="sprite vote"> </span>
You can easily add more states to the sprites like 'hover' and 'active' just the same way. SO even puts all the images for the whole page in a single image. You can verify this with firebug or the Chrome developer tools. Look for 'sprites.png'.
Update (2020)
It's been 10 years since I answered this question and in this time,
the landscape has changed. Now you can use inline svg as well to achieve this effect. I've updated the code snippet to use svg. This is how stackoverflow currently does this.
It works by toggling the color property of a surrounding span element on button click. The span element contains an inline svg image of an arrow. The fill property of the path that makes up the arrow is initialized with currentColor, which instructs it to take whatever is the current text color.
for (const btn of document.querySelectorAll('.vote')) {
btn.addEventListener('click', event => {
event.currentTarget.classList.toggle('on');
});
}
.vote {
display: inline-block;
cursor: pointer;
color: #687074
}
.vote.on {
color: #f48024
}
Click to vote (using svg):
<span class="vote">
<svg width="36" height="36">
<path d="M2 10h32L18 26 2 10z" fill="currentColor"></path>
</svg>
</span>
You can do it by using two simple images ... design two images in some image editors like Photoshop, if u don't have MSPaint...
CSS code is
#voting{
width:30px;
height:40px;
}
.upvote{
width:30px;
height: 20px;
cursor: pointer;
}
.downvote{
width:30px;
height: 20px;
background: url('downvote.jpg') 0 0 no-repeat;
cursor: pointer;
}
HTML code :
<div id="voting">
<div class="upvote"></div>
<div class="downvote"></div>
</div>
I'm doing project on django, and I'm trying to implement up-vote and down-vote on many posts, I've taken #Jan's code partly and finished it.
vote.html
<span onclick="like_function({{user_answer.pk}})" id="like-{{user_answer.pk}}" class="vote_up_off"></span>
<div id="counter-{{user_answer.pk}}">0</div>
<span onclick="dislike_function({{user_answer.pk}})" id="dislike-{{user_answer.pk}}" class="vote_down_off"></span>
vote.css
/* like dislike button */
.vote_up_off {
display: inline-block;
overflow: hidden;
width: 40px;
height: 25px;
cursor: pointer;
background: url(' https://i.stack.imgur.com/nxBdX.png');
background-position: 0 -25px;
margin-left: 5px;
}
.vote_up_on {
background-position: 0 2px;
display: inline-block;
overflow: hidden;
width: 40px;
height: 25px;
cursor: pointer;
background: url('https://i.stack.imgur.com/nxBdX.png');
margin-left: 5px;
}
.vote_down_off {
display: inline-block;
overflow: hidden;
width: 40px;
height: 25px;
cursor: pointer;
background: url('https://i.stack.imgur.com/vWw7n.png');
background-position: 0 -1px;
margin-top: 3px;
}
.vote_down_on {
display: inline-block;
overflow: hidden;
width: 40px;
height: 25px;
cursor: pointer;
background: url('https://i.stack.imgur.com/vWw7n.png');
background-position: 0 -28px;
margin-top: 3px;
}
vote.js
function like_function(answer_id) {
var like_button = document.getElementById('like-'+answer_id);
var dislike_button = document.getElementById('dislike-'+answer_id);
var counter_element = document.getElementById('counter-'+answer_id);
let current_counter = parseInt(counter_element.innerText);
//check if dislike is on(true) or off(false)
let dislike_state = false
if (dislike_button.className == "vote_down_on") {
dislike_state = true
}
else {
dislike_state = false
}
//if dislike is checked
if (dislike_state) {
current_counter += 2;
dislike_button.className = 'vote_down_off'
counter_element.innerText = current_counter
like_button.className = 'vote_up_on'
}
// if dislike is not checked
else {
if (like_button.className == 'vote_up_off') {
like_button.className = "vote_up_on"
current_counter += 1;
counter_element.innerText = current_counter
}
else {
like_button.className = "vote_up_off"
current_counter += -1;
counter_element.innerText = current_counter
}
}
}
function dislike_function(answer_id) {
var like_button = document.getElementById('like-'+answer_id);
var dislike_button = document.getElementById('dislike-'+answer_id);
var counter_element = document.getElementById('counter-'+answer_id);
let current_counter = parseInt(counter_element.innerText);
//check if like is on(true) or off(false)
let like_state = false
if (like_button.className == "vote_up_on") {
like_state = true
}
else {
like_state = false
}
//if like is checked
if (like_state) {
console.log('это тру лайк (лайк нажат)')
current_counter += -2;
like_button.className = 'vote_up_off'
counter_element.innerText = current_counter
dislike_button.className = "vote_down_on"
}
//if like is not checked
else {
if (dislike_button.className == 'vote_down_off') {
dislike_button.className = "vote_down_on"
current_counter += -1;
counter_element.innerText = current_counter
}
else {
dislike_button.className = "vote_down_off"
current_counter += 1;
counter_element.innerText = current_counter
}
}
}