How to clear input with :after element - javascript

Take a look at this website. There are 2 search bars and after each search bar there is an :after element. When you click that element the text box is cleared. How can I do this with Javascript ? (no jquery)

You can't add event listeners to pseudo-elements. But here the element has no contents except the pseudo-element, so you can just add the event listener to the element.
var input = document.getElementById('input');
document.getElementById('clear').addEventListener('click', function() {
input.value = '';
});
#clear::after {
content: '\00d7';
cursor: pointer;
}
<input id="input" value="Hello" />
<span id="clear" title="Clear"></span>

The click event is actually not on the :after pseudo-element, but on the span itself (as you can see here) The pseudo-element just provides the icon, nothing fancy going on here. Then it's just a matter of doing something like this;
element.addEventListener('click', function() {
document.getElementById('startInput').value = '';
}, false);

I don't think it's anything special.
Something like this:
var elementList = document.getElementsByClassName('something');
for (var i = 0; i < elementList.length; i++) {
elementList[i].addEventListener("click", delFn);
}
function delFn(){
console.log("delete it");
}
https://jsfiddle.net/5w4obgzu/1/

Related

Cancel :active element styling

I have DOM elements with :active CSS styling. If a user makes a click, but never releases the click, I want to be able to cancel the :active styling through Javascript.
I have tried doing document.activeElement.blur() but that doesn't work when the user does not release the click. (See fiddle here.)
How can I force blur an element if the user doesn't release their click?
#bobdye's example doesn't work because <div> elements aren't "focusable" by default.
You can force this behaviour by assigning a tabindex property to the div, here is a fiddle.
HTML
<div class="defocus">.::.:.:.::.</div>
<div class="defocus">:..:.:.:..:</div>
<div class="defocus">.::.:.:.::.</div>
You add the class="defocus" attribute to any element that needs to blur after x seconds.
CSS (relevant)
div:active {
color:lightcoral;
}
JavaScript
(function () {
window.addEventListener("load", function () {
var seconds = 0.15 * 1000;
var defocused = document.getElementsByClassName("defocus");
for (var i = 0, l = defocused.length; i < l; i++) {
var el = defocused[i];
el.style.outline = 0; //optional
el.setAttribute("tabindex", -1);
el.addEventListener("mousedown", blur);
}
function blur(e) {
var el = e.target;
setTimeout(function (el) {
el.blur();
}, seconds, el);
}
});
})();
First we wrap this function in a seaf just as a commodity (it will prevent the blur function and variables from being accessible).
Then we get all the elements with a defocus class.
Then we iterate over them.
First we eliminate the focus outline some browsers use because it looks ugly in a div, but it's up to you.
Then we set a tabindex="-1". Using -1 as an index prevents it from acting as a tab break point but allows it to recieve focus and blur events.
Finally we add the blur() function to the mousedown event which will defocus de element after x seconds.
Then we define the blur() function which will take care of defocusing the element with a setTimeout().
That's it, hope it helps!
Note: I don't particularly care for the bounty, keep your rep!
Note: Thanks to #Adam for pointing out that seaf's variables need the var prefix to prevent them from being global.
This Fiddle a simple example of canceling the active state if the user holds the mouse down for more than 500ms.
It uses a link:
<a id="testlink" href="#">Click this</a>
styled to be red if active, and this Javascript:
var lnk = document.getElementById('testlink');
var mousedown = false;
var timerId = null;
lnk.addEventListener('mousedown', function(e) {
mousedown = true;
timerId = window.setTimeout(function() {
if (mousedown) {
lnk.blur();
}
}, 500);
});
lnk.addEventListener('click', function(e) {
mousedown = false;
window.clearTimeout(timerId);
});
Obviously not customized for your particular case, but a "proof of concept".
to be added to other answers, you may use a transition (delayed or not):http://codepen.io/anon/pen/LEXZGB
*:active {
background: red;
filter:blur(5px);
transition: filter 3s 1s;
}
<script src='http://s.codepen.io/assets/libs/prefixfree.min.js'></script>
see me blured if you click too long.

Change backgroundcolour of input after onblur automatically across page

I would like an input field to have the background colour changed after onblur. Automatically for all fields on every page. So I am hoping for a script in the header that will automatically affect all input fields.
Can this be done?
Thanks!
window.onload = function(){
Array.prototype.slice.call(document.getElementsByTagName('input')).forEach(function(element){
element.addEventListener('blur',function(){
//anything here. Notice that both this and element refer to each input element.
})
});
}
document.querySelectorAll or any function returning a NodeList object can be used.
since you start up in an "onblur" state, you should listen to the focus/click event, not the blur event
add css
input{ /*Blurred state*/
background-color: red;
}
.onFocus input{ /*clicked state*/
background-color: green;
}
add some javascript
$(input).
click(function(e){
body.className="onFocus";
}).
blur(function(){
body.className="";
});
It can certainly be done. Because you've demonstrated no attempt, I'm choosing to assume you're willing to support the latest/up-to-date browsers (rather than all legacy browsers):
function colorOnBlur(){
this.style.backgroundColor = '#f00';
}
var inputs = document.querySelectorAll('input');
for (var i = 0, len = inputs.length; i < len; i++){
inputs[i].addEventListener('blur', colorOnBlur);
}
JS Fiddle demo.
Or you can add a new class-name to the elements (rather than changing the style object yourself:
function colorOnBlur(){
this.classList.add('blurred');
}
var inputs = document.querySelectorAll('input');
for (var i = 0, len = inputs.length; i < len; i++){
inputs[i].addEventListener('blur', colorOnBlur);
}
Coupled with the CSS:
input.blurred {
background-color: #f00;
}
JS Fiddle demo.
Obviously, adjust the relevant colours to your own tastes/requirements.
References:
addEventListener().
classList.
document.querySelectorAll().

Enable disable buttons html5/css/javascript

i have made a calculator. i have uploaded it on the following webpage.
www.vipulshree.com
i want to highlight a button on clicking it and remove highlight from it when another button is clicked. when the next button is clicked, it should change color/disable/highlight and the previous button comes back to normal. Please help me ive searched all over the net for this and could not find anything. Help me im desperate.
Thank You.
You can define a class for your buttons and then using the click event you can change its color, and when you click on any button save it in variable say "previous".
So when you click any other button you again change the color of the saved button variable
and assign the current button to that variable.
var previous;
document.getElementsByClassName("className").onclick = function (){
// change the color of the previous element
previous = this;
// change the color of this button
}
Use the :focus CSS pseudo-selector. It will match the element currently having focus. Seems to not work on buttons
Use JavaScript to add a class .focused on click, and remove it on all other elements. Use event delegation on the common parent of all buttons (in this code, it's assumed to be #container).
<script type="text/javascript">
setFocus = function(e) {
if (document.getElementsByClassName('focus')[0]) document.getElementsByClassName('focus')[0].className = '';
if (e.target.tagName.toLowerCase() == 'button') {
e.target.className = 'focus';
}
};
document
.getElementById('container')
.onclick = setFocus;
</script>
My HTML markup looked like this:
<div id="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
Working Example
here is a little jsfiddle working example, it's using jQuery only for the dom ready loader and a CSS class to do the highlight effect.
http://jsfiddle.net/t6bJ3/
var buttons = document.getElementsByTagName('button'),
buttonsLength = buttons.length,
selected,
i = 0,
reset = function() {
for (i = 0; i < buttonsLength; i++) buttons[i].className = '';
},
highlight = function(ev) {
reset();
ev.target.className = 'highlight';
};
for (; i < buttonsLength; i++) buttons[i].onclick = highlight;

How to remove style one click event?

How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources