Skip to content

Instantly share code, notes, and snippets.

@d-adamkiewicz
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-adamkiewicz/74814ec544d304dad734 to your computer and use it in GitHub Desktop.
Save d-adamkiewicz/74814ec544d304dad734 to your computer and use it in GitHub Desktop.
Simple back-forward text data widget example (pure JS, IE8)
<!DOCTYPE html>
<html>
<head>
<title>Simple widget</title>
<meta charset="utf-8" />
<style type="text/css">
</style>
</head>
<body>
<button id="back">&lt;&lt;</button>
<!--<input type="text" id="data_input" readonly="readonly" data-id="2" />-->
<input type="text" id="data_input" readonly="readonly" data-id="4" />
<button id="forward">&gt;&gt;</button>
<script>
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}
function search(element) {
return element.id == this;
}
var data = [
{id:1, name:'Some data'},
{id:2, name: 'Some data 2'},
{id:3, name: 'Some data 3'},
{id:4, name: 'Some data 4'}
];
var dataInput = document.querySelector('#data_input');
var bBt = document.getElementById("back"),
fBt = document.getElementById("forward");
function setData(oper) {
var dataId = dataInput.getAttribute("data-id")
, inputVal = ''
, tmpIndex = '';
if (dataId == null) {
inputVal = data[0].name;
bBt.disabled = true;
dataInput.setAttribute("data-id", data[0].id);
} else {
tmpIndex = data.findIndex(search, dataId);
tmpIndex = tmpIndex + oper;
if (tmpIndex == 0) {
bBt.disabled = true;
} else if (tmpIndex>0 && tmpIndex <data.length-1) {
bBt.disabled = false;
fBt.disabled = false;
} else if (tmpIndex == data.length-1) {
fBt.disabled = true;
}
inputVal = data[tmpIndex].name;
dataInput.setAttribute("data-id", data[tmpIndex].id);
}
dataInput.value = inputVal;
}
setData(0);
if (bBt.addEventListener) {
bBt.addEventListener('click', function(e) {
setData(-1);
}, false);
} else if (bBt.attachEvent) {
bBt.attachEvent('onclick', function(e) {
setData(-1);
});
}
if (fBt.addEventListener) {
fBt.addEventListener('click', function(e) {
setData(1);
}, false);
} else if (fBt.attachEvent) {
fBt.attachEvent('onclick', function(e) {
setData(1);
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment