How to save the sort order? - javascript

I have created Demo by using packery and draggabilly where I have five grids.I can sort them using the draggable.After I make my sort.I need to save the sorted grid.Here the grids are not moving when I inspect in dev only the position is changing not the grid exactly.
As I've passed ids,but of no use.Due to the issue mentioned above.
Is there any way of saving the sort order ? I don't want to use localStorage
My code follows
HTML
<h1>Image sort</h1>
<div class="packery">
<div class="item w2 h2 i1" tabindex="0">A</div>
<div class="item w2 h2 i2" tabindex="1">B</div>
<div class="item w2 h2 i3" tabindex="2">C</div>
<div class="item w2 h2 i4" tabindex="3">D</div>
<div class="item w2 h2 i5" tabindex="4">E</div>
</div>
JS
// http://packery.metafizzy.co/packery.pkgd.js and
// http://draggabilly.desandro.com/draggabilly.pkgd.js added as external resource
// ----- text helper ----- //
$(function() {
var $container = $('.packery').packery({
columnWidth: 100,
rowHeight: 180,
// disable initial layout
isInitLayout: false
});
var pckry = $container.data('packery');
// ----- packery setup ----- //
// trigger initial layout
$container.packery();
var itemElems = $container.packery('getItemElements');
// for each item element
$( itemElems ).each( function( i, itemElem ) {
// make element draggable with Draggabilly
var draggie = new Draggabilly( itemElem );
// bind Draggabilly events to Packery
$container.packery( 'bindDraggabillyEvents', draggie );
});
CSS
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body { font-family: sans-serif; }
.packery {
background: #FDD;
background: hsla(45, 100%, 40%, 0.2);
max-width: 460px;
}
/* clearfix */
.packery:after {
content: ' ';
display: block;
clear: both;
}
.item {
width: 240px;
height: 140px;
float: left;
background: #C09;
border: 4px solid #333;
border-color: hsla(0, 0%, 0%, 0.3);
font-size: 20px;
color: white;
padding: 10px;
}
.item:hover {
border-color: white;
cursor: move;
}
.item.w2 { width: 400px; }
.item.h2 { height: 140px; }
.item.w2.i1 { background: #ffff00; }
.item.w2.i2 { background: #ff6633; }
.item.w2.i3 { background: #00c6d7; }
.item.w2.i4 { background: #990099; }
.item.w2.i5 { background: #EEEEEE; }
.item.is-dragging,
.item.is-positioning-post-drag {
border-color: white;
background: #09F;
z-index: 2;
}

Well 'save' can mean two things.
Saving the values temporarily like localStorage/Cookies as you mentioned in the question. The thing is that, it will solve your problem of saving the order in the client, even if the user refreshes the page and comes back, he/she can check these values and reorder them accordingly. Disadvantage is that, if the user deletes his/her cache and history, the data might not be there when he/she revisits the page.
And the other alternative would be to use traditional approach, that is, to use a Ajax call and send data to a back-end script(PHP or Nodejs) that will save the values to a DB. This way, if there exists a login system of sorts, you can just post the values to a database and proceed in that manner.
Here is a simple code to give you an idea (using PHP):
JS
$.ajax({
url: 'test.php',
type: 'POST',
data: {order : sortOrder},
success: function(result){
// do something
}
});
test.php
$order = $_REQUEST['order'];
echo $order;
// Do something here that will store the values to the database
For Nodejs, you can do something similar to this: How to send array of ids correctly in express
Hope it helps...

Found this codepen which seems very similar to your example.
Packery.prototype.sortItems = function( keys, getSortKey ) {
// copy items
//var _items = this.items.slice(0);
var itemsBySortKey = {};
var key, item;
for ( var i=0, len = this.items.length; i < len; i++ ) {
item = this.items[i];
key = getSortKey( item );
itemsBySortKey[ key ] = item;
}
i=0;
len = keys.length;
var sortedItems = [];
for ( ; i < len; i++ ) {
key = keys[i];
item = itemsBySortKey[ key ];
this.items[i] = item;
}
};
var storedSortOrder = localStorage.getItem('sortOrder')
if ( storedSortOrder ) {
storedSortOrder = JSON.parse( storedSortOrder );
pckry.sortItems( storedSortOrder, function( item ) {
return item.element.getAttribute('tabindex');
});
}

It might not be a full answer, but might be helpful, you could create a function from it
var saved_order = {};
Object.keys(object_to_sort)
.sort()
.forEach(function(key, i) {
console.log('new order: ' + key, ':', object_to_sort[key]);
saved_order[key] = object_to_sort[key];
});

Related

localstorage of a classlist

soo, i am trying to use localstorage to store the classlist so it will remember whether or not something was added to their favorites list. i need to do this with JavaScript. The error provided comes from the console in my web browser (chrome)
The ERROR
main.js:99 Uncaught TypeError: Cannot read property 'value' of undefined
at storeFavo (main.js:99)
at HTMLButtonElement.favorites (main.js:71)
HTML
<!-- Showcase -->
<section class="showcase">
<div class="container grid ">
<div class="showcase-form card">
<h2>*Input Car Name*</h2>
<img alt="" src="#" >
<button id="favo" class="btn">Add to Favorites</button>
<button id="info" class="btn">More Info</button>
</div>
</div>
</section>
JavaScript
window.addEventListener('load', init);
const info = document.querySelector('#info');
const div1 = document.querySelector('.moreInfo');
const favo = document.querySelector('#favo');
let apiUrl = 'webservice/includes/actions.php';
let apiUrl2 = 'webservice/index.php';
let Favos = document.getElementById('favo').getElementsByClassName('favorited')[0];
function init() {
info.addEventListener('click', moreInfo);
favo.addEventListener('click', favorites);
if (typeof window.localStorage === "undefined") {
console.error('Local storage is not available in your browser');
return;
}
checkFromLocalStorage()
carList;
}
function carList() {
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(getAjaxSuccessHandler)
.catch(getAjaxErrorHandler);
}
function getAjaxSuccessHandler(data) {
console.log(data);
}
function getAjaxErrorHandler(data) {
console.error(data);
}
// Generate Cards
// getCars.map((item)=>{
// return (
// <div>
// <p> {item.brand}</p>
// <p> {item.type}</p>
// </div>
// );
// }),
// More Info Button
function moreInfo() {
let title= document.createElement('h1');
title.innerHTML = 'Info';
div1.appendChild(title)
console.log("info?")
if (div1.style.display == 'block'){
div1.style.display = 'none';
} else {
div1.style.display = 'block';
}
}
// Add To Favorites Button
function favorites() {
console.log("favo")
if (favo.classList == 'btn') {
favo.classList.remove('btn')
favo.classList.add('favorited')
favo.innerHTML = 'Remove from favorites';
storeFavo()
}
else {
favo.classList.remove('favorited')
favo.classList.add('btn')
favo.innerHTML = 'Add to Favorites';
deleteClickHandler()
}
}
//Check
/**
* Is local storage is available on page load? Let's fill the form
*/
function checkFromLocalStorage() {
if (localStorage.getItem('favos') !== null) {
Favos.value = localStorage.getItem('favos');
}
}
//Store
/**
* After submitting the form, let's save the values in the local storage
*
* #param e
*/
function storeFavo(e) {
localStorage.setItem('favos', Favos.value);
localStorage['Favos'] = document.getElementById("favo")
}
//Delete
/**
* Make sure we clean up the local storage again
*
* #param e
*/
function deleteClickHandler(e) {
localStorage.removeItem('favos');
}
CSS
.favorited {
display: inline-block;
padding: 10px 30px;
cursor: pointer;
background: #470aed;
color: #ffffff;
border: none;
border-radius: 5px;
}
.btn {
display: inline-block;
padding: 10px 30px;
cursor: pointer;
background: var(--primary-color);
color: #ffffff;
border: none;
border-radius: 5px;
}
I will do my very best to respond fast and to provide any needed information if asked for.
Check the documentation of localStorage.setItem https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem, you can write only string values, but you are trying to write an Object value (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName). If you want to have some persistence fo your HTML element, you can save outerHTML https://developer.mozilla.org/ru/docs/Web/API/Element/outerHTML to the storage and parse it on load.

Store entry index page to cookie and send visitor back to that index page regardless of folder

I have a site that will have a slightly different homepage / index page depending on which state a visitor is from. Now, let's say a visitor enters the site via, for example, https://www.example.com/FLORIDA/index.html, if they then browse around and click a top level page like https://www.example.com/about.html and then click the homepage link somewhere on that page, I'd like them to actually return to the https://www.example.com/FLORIDA/index.html homepage that they entered the session/visit from rather than go to the default index.html.
Pages like About Us, Terms, Privacy, Contact, etc. will all obviously be top folder pages. So, if someone enters the site via /FLORIDA/index.html and then visits about.html, if they then click the homepage link at the top of about.html, they would go to default index.html. So is it possible to store the fact that they entered the site via https://www.example.com/FLORIDA/index.html to a cookie and return them to that index page if they browse around and then click a homepage link from elsewhere in the site?
Simple version - visit any /state/index.html and the state is remembered in localStorage
You include JS on each page (using external JS file) where you have a home URL - the link needs id="home"
The script ASSUMES that you have ALWAYS yourserver.com/state/index.html
If not you need to change the ternary
let state = parts.length === 3 ? parts[1] : "";
Here is the code to copy
window.addEventListener("load", function() { // when page loads
const url = new URL(location.href);
const parts = url.pathname.split("/"); // creates ["","page.html"] OR ["","state","index.html"]
let state = parts.length === 3 ? parts[1] : ""; // get the state from the URL OR
if (state === "") { // get the state from localStorage instead
state = localStorage.getItem("state") || "";
}
if (state) { // do we NOW have a state?
localStorage.setItem("state",state);
url.pathname = state ? "/"+state+"/index.html" : "/index.html";
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
}
})
Because the stacksnippets do not support localStorage, you need to uncomment and delete lines when you copy the code to your server.
window.addEventListener("load", function() { // when page loads
// const url = new URL(location.href); // uncomment on your server
const url = new URL("https://yourserver.com/florida/index.html"); // remove when on your server
const parts = url.pathname.split("/"); // creates ["","page.html"] OR ["","state","index.html"]
console.log(parts)
let state = parts.length === 3 ? parts[1] : ""; // get the state from the URL OR
if (state === "") { // get the state from localStorage instead
// state = localStorage.getItem("state") || ""; // uncomment on your server
}
if (state) { // do we NOW have a state?
// localStorage.setItem("state",state); // uncomment on your server
url.pathname = state ? "/"+state+"/index.html" : "/index.html";
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
}
})
<a id="home" href="index.html">Home</a>
Full example
The code below does the following
sets the active page based on the URL so you need to match about to about - case sensitive
sets the state from localStorage if already set before
sets the state from dropdown. It could reload the page if needed
window.addEventListener("load", function() { // when page loads
// const url = new URL(location.href); // uncomment on your server
const url = new URL("https://yourserver.com/tutorials"); // remove when on your server
const ul = document.getElementById("links");
// let state = localStorage.getItem("state") || ""; // uncomment on your server
let state = "FLORIDA"; // remove from code on your server
// state selection
const stateSel = document.getElementById("stateSel");
if (state) { // already have a state
stateSel.value=state;
}
stateSel.onchange=function() { // using onchange to trigger later
state = this.value;
// localStorage.setItem("state",state); // uncomment on your server
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
};
stateSel.onchange(); // set the link when loading page
// active link
[...ul.querySelectorAll("li")].forEach(function(li) {
const page = li.getAttribute("data-page");
li.querySelector("a").classList.toggle("active", url.pathname.indexOf(page) != -1); // set active
})
})
/* from https://css-snippets.com/simple-horizontal-navigation/ */
.nav ul {
list-style: none;
background-color: #444;
text-align: center;
padding: 0;
margin: 0;
}
.nav li {
font-family: 'Oswald', sans-serif;
font-size: 1.2em;
line-height: 40px;
height: 40px;
border-bottom: 1px solid #888;
}
.nav a {
text-decoration: none;
color: #fff;
display: block;
transition: .3s background-color;
}
.nav a:hover {
background-color: #005f5f;
}
.nav a.active {
background-color: #fff;
color: #444;
cursor: default;
}
#media screen and (min-width: 600px) {
.nav li {
width: 120px;
border-bottom: none;
height: 50px;
line-height: 50px;
font-size: 1.4em;
}
<div class="nav">
<ul id="links">
<li data-page="/index"><a id="home" href="index">Home</a></li>
<li data-page="/tutorials">Tutorials</li>
<li data-page="/about">About</li>
<li data-page="/news">Newsletter</li>
<li data-page="/contact">Contact</li>
</ul>
</div>
<select id="stateSel">
<option value="">Which state?</option>
<option value="FLORIDA">Florida</option>
<option value="NEVADA">Nevada</option>
</select>

Javascript Less Sorter

Problem:
I want to make a Less-sorting script for myself. When i enter Less Code in the textarea and click the button, p#result should output the sorted Less Code.
The Less Code should be sorted like this:
{
Mixins(They all start with ".mx")
Properties(Sorted in alphabetic Order)
}
Here is what i have got so far:
index.html:
<head>
<script src="jquery.min.js"></script>
</head>
<textarea id="input" style="width: 600px; height: 300px; resize: none;">
</textarea>
<p id="result" style="max-width: 600px; word-wrap: break-word;"></p>
<button>Sort</button>
<script src="jquery.sorter.js"></script>
jquery.sorter.js:
var result = "",
mixins = "",
properties = "";
$("button").on("click", function () {
var textarea = $('#input').val().split('\n');
function checkLine(position) {
var index;
for (index = position; index < textarea.length; ++index) {
var line = textarea[index].trim();
if (line.includes("{") === true)
{
result = result + mixins + "<br>" + properties + line + "<br>";
mixins = "";
properties = "";
checkLine(index + 1);
} else if (line.includes("}") === true)
{
result = result + mixins + properties + line + "<br>";
mixins = "";
properties = "";
break;
} else if (line.includes(".mx") === true)
{
mixins = mixins + line + "<br>";
} else if (line.includes(":") === true)
{
properties = properties + line + "<br>";
} else
{
result = result + "<br>";
}
console.log(index + ": " + mixins + " " + properties);
}
}
checkLine(0);
$("p#result").append(result);
$("button").hide();
});
If i enter this:
.frame {
color: blue;
background-color: white;
.mx-hello(white);
.framesecond {
font-size: 12px;
background: green;
.mx-test(white);
}
}
I should get al least this output: (I didnt think of a sorting mechanism yet... :D)
.frame {
.mx-hello(white);
color: blue;
background-color: white;
.framesecond {
.mx-test(white);
font-size: 12px;
background: green;
}
}
But i get this Output:
.frame {
.mx-hello(white);
color: blue;
background-color: white;
.framesecond {
.mx-test(white);
font-size: 12px;
background: green;
}
.mx-test(white);
font-size: 12px;
background: green;
}
.mx-hello(white);
color: blue;
background-color: white;
.framesecond {
.mx-test(white);
font-size: 12px;
background: green;
}
.mx-test(white);
font-size: 12px;
background: green;
}
Background - Story:
I work for a Web-Development Company. My Less Code always looks a bit messy, but we have guidelines how to format our Code. If im done with a Project i always sit there hour for hour just rearranging Less Code. Then i thought to myself: "There must be an easier solution for my problem!". So i googled and googled and nothing really worked. Then i decided to try it myself and thats why i am here!
I hope you understand my Problem, if something is unclear please let me know so i can edit my Question! (Im not so good at javascript, so any help is appreciated! :D)
I took a look at it to see if I could solve this one. Check this out:
Codepen: https://codepen.io/huppys/pen/VrbxLd?editors=1010
I replaced the string.includes("something") with some regular expressions to be able to filter even for some different kind of less expressions.
Plus: Properties get sorted. After finding a property the string describing the property gets pushed into an array. Before adding the found properties to the output string they get sorted.
Side note: What IDE or editor are you using for writing your LESS code? Probably it could take care of the syntax sorting itself?

Can I save my selection (Theme switch) in HTML?

I am trying to make a basic theme switching code using HTML and JavaScript. But if I hit back or refresh, the selection is cancelled and the page is back to normal.
Can I add any function in JavaScript so that the selection stays till cache clean or something like that?
var x = 0;
var themeValue = 0;
function changeTheme3() {
themeValue ++;
if (themeValue > 2) {
themeValue = 1;
}
if (themeValue == 1) {
document.body.style.backgroundColor = "grey";
} else if (themeValue == 2) {
document.body.style.backgroundColor = "white";
}
}
button {
display: block;
margin: 0 auto;
padding: 0;
width: 250px;
height: 70px;
border: 2px solid #1ECD97;
border-radius: 40px;
background: transparent;
color: #1ECD97;
letter-spacing: 1px;
font-size: 18px;
font-family: 'Montserrat', sans-serif;
}
button:hover {
background-color: #1ECD97;
color: #fff;
}
<div id="theme-button">
<button type="button" onclick="changeTheme3()">Change Theme</button>
</div>
I'd suggest making use of LocalStorage. If you want the user to be able to customize their experience, you need to save that somewhere. This is typically done through a Session or Database, however both of those are back-end solutions.
For front-end, you have the options of setting a cookie or using localstorage. If you want the theme selection to be limited to a single session, you can also use sessionStorage
For implementation
function changeTheme3() {
themeValue ++;
if (themeValue > 2) {
themeValue = 1;
localStorage.setItem('themeValue', themeValue);
}
if (themeValue == 1) {
document.body.style.backgroundColor = "grey";
} else if (themeValue == 2) {
document.body.style.backgroundColor = "white";
}
}
Then, somewhere when you load a page, you need to pull this value from storage. (Note, localStorage saves values as strings, so you may want to parseInt() your value when retrieving).
function loadTheme(){
if (localStorage && localStorage.getItem('themeValue'){
var storedTheme = parseInt(localStorage.getItem('themeValue'));
//do your logic to set the theme based on value
} else {
//do nothing or choose to set your default theme as the value into storage
}
}
One side note, depending on which browsers you are supporting, you may want to make sure you're checking to see if localStorage is supported. It has good support for any modern browser.
you can do that using sqlite html5 for example check this link http://www.html5rocks.com/en/tutorials/webdatabase/todo/ :D
here for simple example sir
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('db', '1.0', 'theme selector', 1000); //db name, version, desc, size in byte
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS THEME (id unique, theme)');
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM THEME WHERE id = 1', [], function (tx, results) {
var len = results.rows.length, i;
var value = 'theme_1';
if(len == 0 ){
tx.executeSql('INSERT INTO THEME (id, theme) VALUES (1, ?)', [value]);
}else{
value = results.rows.item(0).theme;
}
document.querySelector('#theme_selected').innerHTML = value;
document.getElementById('theme_select').value = value;
}, null);
});
function update (){
var selector = document.getElementById('theme_select');
var value = selector[selector.selectedIndex].value;
db.transaction(function (tx) {
tx.executeSql('UPDATE THEME SET theme = ? WHERE id=1', [value]);
document.querySelector('#theme_selected').innerHTML = value;
});
}
</script>
</head>
<body>
<select id="theme_select">
<option value="theme_1" >theme 1</option>
<option value="theme_2">theme 2</option>
</select>
<button onclick="update()">update</button>
<div id="theme_selected"></div>
</body>
</html>

How to bind click event on image added using CSS 'background-image' property in jQuery

Here is my fiddle link
I guess my question is clear by title itself. Still, what I am looking for is an way to bind click event on the image added using css's background-image property.
I know, I could have achieved the similar functionality (of placing image over input field using this way or this way) by simply positioning <img> tag over input box and then handling the required events but that way didn't seem too flexible with input fields of varying width and height or if the wrapping div doesn't have position:relative; as its property.
If adding event on image loaded with background-image is not possible then how to make the later approach more flexible.
Hope I have conveyed my issues clearly.
Thanks.
Something like this appears to also work:
$('.cross').click(function(e) {
var mousePosInElement = e.pageX - $(this).position().left;
if (mousePosInElement > $(this).width()) {
$(this).val('');
}
});
Link to example
So you need to bind the click event to the image but not using an embebed attributte that's really a very good and dificult question by the way.
I know my approach is complicated but is the only I can figure right now.
You can get the image size (widthImage and heightImage) and know the position relatives of one to another (here is a way of calculating a position of an objet relative to anohter:jQuery get position of element relative to another element) you may use it to calculate the position of the input in the whole screen
and try something like this:
$(document).ready(function(){
$('body').on('click', 'input.cross', function (e) {
var widthInput = parseInt($(this).css('width'),10);
var heightInput = parseInt($(this).css('height'),10);
var position = $(this).position();
var top = position.top;
var left = position.left;
var sizesRelativesInPercentage = $(this).css('background-size').split(/ +/);
var widthPorcentage = parseInt(sizesRelativesInPercentage[0],10);
var heightPorcentage = parseInt(sizesRelativesInPercentage[1],10);
var widthImage = (widthInput * widthPorcentage)/100;
var heightImage = (heightInput * heightPorcentage)/100;
var xFinalImageFinish= (left+widthInput);
var yFinalImageFinish = (top+heightInput);
// Fire the callback if the click was in the image
if (e.pageX >= xFinalImageStart && e.pageX <= xFinalImageFinish &&
e.pageY >= yFinalImageStart && e.pageY <= yFinalImageFinish) {
// Prevent crazy animations and redundant handling
$(this).off('click');
alert('click on the image');
//Do whatever you want
}
});
});
This is only an idea...I am trying to make a fiddle about this, hope so :O
As pointed out by #Felix King
Since the image is not an element in the document, it does not trigger
events and you cannot bind a handler to it. You have to use a
workaround.
Here is a possible work-around (in jquery, but could just as easily be POJS).
CSS
.wrapper {
padding: 1px;
display: inline-block;
border: 2px LightGray inset;
}
.wrapperFocus {
border: 2px DarkGray inset;
}
.textInput {
padding: 0;
border:none;
outline: none;
height: 20px;
width: 150px;
}
.cross {
float: right;
height: 20px;
width: 20px;
background-image:url('http://s20.postimg.org/6125okgwt/rough_Close.png');
background-repeat:no-repeat;
background-position: center;
background-size:90%;
cursor: pointer;
}
HTML
<fieldset class="wrapper">
<input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<fieldset class="wrapper">
<input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<fieldset class="wrapper">
<input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<hr>
<button>submit</button>
Javascript
$(document).on("click", "span.cross", function () {
$(this).prev().val("");
}).on("focus", "input.textInput", function () {
$(this).parent().addClass("wrapperFocus");
}).on("blur", "input.textInput", function () {
$(this).parent().removeClass("wrapperFocus");
});
On jsfiddle
Or if you want to do it without the additional CSS and HTML, then this should be cross-browser (POJS as you already have a jquery example).
CSS
.cross {
height: 20px;
width: 150px;
background-image:url('http://s20.postimg.org/6125okgwt/rough_Close.png');
background-repeat:no-repeat;
background-position:right center;
background-size:10% 90%;
z-index: -1;
padding-right: 6%;
}
HTML
<input type="text" class="cross" />
<input type="text" class="cross" />
<input type="text" class="cross" />
<hr>
<button>submit</button>
Javascript
function normalise(e) {
e = e || window.event;
e.target = e.target || e.srcElement;
return e;
}
var getWidth = (function () {
var func;
if (document.defaultView.getComputedStyle) {
func = document.defaultView.getComputedStyle;
} else if (target.currentStyle) {
func = function (t) {
return t.currentStyle;
}
} else {
func = function () {
throw new Error("unable to get a computed width");
}
}
return function (target) {
return parseInt(func(target).width);
};
}());
function isInputCross(target) {
return target.tagName.toUpperCase() === "INPUT" && target.className.match(/(?:^|\s)cross(?!\S)/);
}
function isOverImage(e) {
return (e.clientX - e.target.offsetLeft) > getWidth(e.target);
}
function clearCrossInput(e) {
e = normalise(e);
if (isInputCross(e.target) && isOverImage(e)) {
e.target.value = "";
}
}
document.body.onclick = (function () {
var prevFunc = document.body.onclick;
if ({}.toString.call(prevFunc) === "[object Function]") {
return function (ev) {
prevFunc(ev);
clearCrossInput(ev);
};
}
return clearCrossInput;
}());
On jsfiddle
But if you want the cursor to change when hovered over the position then you will need to do some extra work. Like this (you could just as easily do this with jquery too).
Javascript
function hoverCrossInput(e) {
e = normalise(e);
if (isInputCross(e.target)) {
if (isOverImage(e)) {
e.target.style.cursor = "pointer";
return;
}
}
e.target.style.cursor = "";
}
document.body.onmousemove = (function () {
var prevFunc = document.body.onmousemove;
if ({}.toString.call(prevFunc) === "[object Function]") {
return function (ev) {
prevFunc(ev);
hoverCrossInput(ev);
};
}
return hoverCrossInput;
}());
On jsfiddle
I do something similar by using an <input type="text" ... > immediately followed by an <input type="button">
The button is given a background image and positioned-relative to move it into the text field; essentially...
position: relative;
top: 4px;
right: 1.6em;
height: 16px;
width: 16px;
border: none;
Then I just add a dead-plain click handler to the button, no computations necessary.
The height x width would depend on your image, and you would tweak the top and right to fit your situation.
This fiddle shows it pared down to the bare essentials.

Categories