Target input with :focus, even when changing - javascript

I have something like this in jQuery
if($("input").is(":focus")){
// do something
}
It has an effect on the focused input like it should. However, when I switch over to a new input that gets the focus instead, the first one is the still having that effect and not the new one. What would be a good way to make it auto update so that the one that is currently focused has the effect? Thanks!

You might use a simple CSS3 rule:
input:focus {
background-color: red;
}

"Do something" on focus; "Undo that thing" on blur
Your example only runs one time and targets only one input: the one with focus. It doesn't respond to changes.
Use jQuery's .on() method to bind event listeners that can respond to changes.
A basic example:
$('input').on('focus', function () {
// do something
$(this).css('background-color','yellow');
});
$('input').on('blur', function () {
// do something
$(this).css('background-color','white');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
Another example using chaining:
$('input')
.on('focus', function () {
$(this).addClass('highlight');
})
.on('blur', function () {
$(this).removeClass('highlight');
});
input.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
Another example using space-separated list of events:
$('input')
.on('focus blur', function () {
$(this).toggleClass('highlight');
});
input.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />

Does this help?
$('input').on('focusin' function(){
$(this).toggleClass('someClass')
});
$('input').on('focusout' function(){
$(this).toggleClass('someClass')
});

If you're using jQuery, you could attach event handlers to the focus and blur events.
http://api.jquery.com/category/events/form-events/
$(someSelector).on('focus', function(evt) {
//do stuff
})
and
$(someSelector).on('blur', function(evt) {
//do stuff
})
Note that you can use focusin and focusout if you need to listen for event bubbling.

Related

How to trigger focusout event

I have a focusout event
$('.alpha').on("focusout", function () {...});
and I want want to trigger it from somewhere else in the code.
I tried $('#input12').focus().blur();
and also tried $('#input12').trigger("focusout")
edit: I am using a dynamically generated elements.
but no luck there...
the element #input12 has the class name alpha so I expect The focusout event to be triggered.
Is there any way of getting it done?
here is a jsfiddle example of when I am trying to do https://jsfiddle.net/jnmnk68d/
You need to delegate your events to a non-dynamic parent element.
In this example, we listen for focusout events on the form but only fire our function if the event's target matches the selector (in this case ".alpha"). This way the event can be fired on any elements that match now or in the future.
$("form").on("focusout", ".alpha", function() {
console.log("focusout happened!");
});
Here's a full demo which allows you to see how using delegated events we are able to trigger the event on dynamically inserted content.
$(function() {
$("form").on("focusout", ".alpha", function(e) {
console.warn("focusout triggered on " + e.target.outerHTML);
});
//example trigger
//click the link to trigger the event
$("a").on("click", function(e) {
e.preventDefault();
$("#input12").trigger("focusout");
});
//demo injecting content
//click the create button then focus out on the new element to see the delegated event still being fired.
var i = 12;
$("form").on("submit", function(e) {
e.preventDefault();
var id = "input" + (++i);
$(this).find("fieldset").append("<input id='" + id + "' class='alpha' placeholder='" + id + "' />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input id="input12" class="alpha" placeholder="input12" />
<input type="submit" value="create new" />
</fieldset>
</form>
trigger on input12
Using [0] on the jQuery element works! Also kontrollanten options works too! And doing a normal trigger on focusout too!
$(".alpha").on("focusout", function(e){
console.log(e.type, true);
});
//option 1
$('#input12')[0].focus(); //vanilla
$('#input12')[0].blur(); //vanilla
//option 2
$('#input12').trigger('focusout');
//option 3
$('#input12').trigger('blur');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="alpha" id="input12" />
Here is a working example taken from the jQuery docs.
var focus = 0,
blur = 0;
$("p")
.focusout(function() {
focus++;
$("#focus-count").text("focusout fired: " + focus + "x");
})
.inputs {
float: left;
margin-right: 1em;
}
.inputs p {
margin-top: 0;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>focusout demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="inputs">
<p>
<input type="text"><br>
<input type="text">
</p>
</div>
<div id="focus-count">focusout fire</div>
</body>
</html>
Maybe if you add your full code I can be of better help?
Hope this helps!
See this code, it will call focusout 1second after focus has happend.
$('.alpha').on("focusout", function() {
console.log('FOCUSOUT!');
});
$('.alpha').on("focus", function() {
var self = $(this);
window.setTimeout(function() {
self.focusout();
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class="alpha" />
I found out what seemed to be wrong with my code..
first of all I changed my event to use delegation and I connected it to a non dynamic element (element that was not added dynamically) just as some here advised.
I also needed to call the trigger function inside a setTimeout because it turns out that it takes a while to render the dynamically added element, so using the setTimeout did the trick.
Thank you all for helping out!

Trying to show element based on whether or not a specific input field has focus

As the title says, I'm trying to figure out how I can show a element based on whether or not a input field has focus our not.
So when the specific input field has focus I need to show a element, and when it has no focus the element should be hidden.
I've tried a lot of different things, and this is my lates try:
<script>
$(".only-oslo-delivery").hide();
if ($("#address_city").is(":focus")) {
$(".only-oslo-delivery").show();
};
</script>
only-oslo-delivery is a < p > tag with the text I want to display when the input field has focus.
address_city is the ID of the input field.
Your code only runs once, you need event handler to execute it as per user actions:
$("#address_city").on('focus', function() {
$(".only-oslo-delivery").show();
}).on('blur', function() {
$(".only-oslo-delivery").hide();
})
.only-oslo-delivery {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address_city">
<p class="only-oslo-delivery">test</p>
You can bind events to your button to show/hide the .only-oslo-delivery element when it is focused and blurred.
$('#address_city').focus(function() {
$('.only-oslo-delivery').show();
}).blur(function() {
$('.only-oslo-delivery').hide();
});
Interestingly if the elements are next to each other on the page you could use adjacent css rules to accomplish this without any javascript.
<input type="text" id="address_city">
<p class="only-oslo-deliver">...</p>
And then use the following css:
.only-oslo-delivery {
display: none;
}
#address_city:focus~.only-oslo-delivery {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address_city">
<p class="only-oslo-delivery">test</p>
.only-oslo-delivery {
display: none;
}
$("#address_city").on('focus', function() {
$(".only-oslo-delivery").show();
}).on('blur', function() {
$(".only-oslo-delivery").hide();
})
You need to use focus event to show and blur to hide:
$("#address_city").on('focus blur', function(e) {
$(".only-oslo-delivery").toggle($('#address_city').is(':focus') && e.type === 'focus');
});
.only-oslo-delivery {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='address_city'>
<p class='only-oslo-delivery'>only-oslo-delivery</p>
.toggle(true/false) would show when true and hide when false.
Here is another way:
var $field = $('#address_city');
var $info = $('.only-oslo-delivery').hide();
$field.on('focus blur', function (e) {
$info.toggle(e.type === 'focus');
});

Trigger drop event

I have a form with an input type="file". I have a div surrounding the input. I then set the input to display:none. In JavaScript, I set that when you select the div, the input gets selected.
That all works nice and dandy, but how can I make it that when you drag a file onto the div, the input should trigger a drop event?
So here's how I would do the click event:
$('#target').click();
I'm looking for something like this:
$('#target').drop();
JSFiddle
$(document).ready(function() {
$('#browseFileDiv').click(function(e) {
$(this).find('input[type="file"]').click();
});
$('#browseFileDiv input').click(function(e) {
e.stopPropagation();
});
});
#browseFileDiv {
height: 200px;
width: 200px;
background-color: orange;
border-radius: 50%;
}
#browseFileDiv > input {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<div id="browseFileDiv">
<input id="openFile" name="img" type="file" />
</div>
</form>
First, you don't need to wrap the <input type="file"> with a div around it and then with javscript trigger the .click() event for that input file if you click the div, make a <label> for this input file and style it, thus you can trigger the click event with HTML only without the need for javascript:
<label for="openFile" id="browseFile"></label>
<input id="openFile" name="img" type="file">
Updated: Then, as in this JS Fiddle the problem is that you need to return false; for the ondragover and ondrop events
var browseFile = document.getElementById('browseFile');
browseFile.ondragover = function () {
return false;
};
browseFile.ondrop = function (event) {
event.preventDefault && event.preventDefault();
var files = event.dataTransfer.files;
console.log(files);
return false;
};
** Note that the above works for multiple files as well.
Resource: http://html5doctor.com/drag-and-drop-to-server/
$('#browseFileDiv').on('drop', function(){/* code here */}) is probably what you're looking for.
You probably really want to use jQuery UI. Click the view source button.

How to onclick outside an input element which is inside a div?

It maybe easy but i can't think anything to find the way when i click outside the textbox to alert something in javascript BUT when i click inside the text nothing to happen.The input text is inside the div element.
So,let's assume that my html is like bellow:
<div id="myone" onclick="javascript: myfunc();">
<input type="text" id="myInput"></input>
</div>
function myfunc()
{
alert('ok');
}
How to change that?
Thank you a lot!
Do this:
var div = document.getElementById('myone');
var funct = function(){
var input = div.querySelector("#myInput");
return false;
};
div.onclick = funct;
You shoud use this condition. e.target !== this
It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
Use it inside your click function like this and see it in action:
$('.divover').on('click', function(e) {
if (e.target !== this) return;
thefunc();
});
var thefunc = function myfunc() {
alert('ok');
}
.divover {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divover'>somelabel:
<span><input type="text" class="as" name="forename"></span>
</div>
This will work, if you do this carefully.
<div id="myone" onclick="javascript: myfunc();">
//your stuff in the clickable division.
</div>
<div style="position:absolute;">
<!--Adjust this division in such a way that, it comes inside your clickable division--><input
type="text" id="myInput"></input>
</div>
//Your script function/code here
function myfunc()
{
alert('ok');
}

How to execute javascript function from a dynamic html result? Jquery

Please have a look at this code -
When I click on myLink I get a modal dialog window which shows the html as defined below. This html includes a button (id=test_button), and when I click on this button I want to do an ajax request.
But its not working. So to test it I am just doing an alert but it wont work as well.
Also will it be possible to update existing dom element values (just populate a form) from within a test_button click function.
Thanks for your help.
$('#myLink').click(function(event) {
event.preventDefault();
$('<div id="iContainer">Test: <input type="text" value="" id="test_text" />
<input type="button" id="test_button" value="click" /></div>').appendTo('body');
$("#iContainer").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#iContainer").remove();
}
});
});
$('#test_button').click(function() {
alert('I am in Alert');
//alert($('#test_text').val());
});
Try with Events/live:
$('#test_button').live("click", function(){
alert('test');
});
The problem is that you're attempting to attach the click handler before the element exists.
As stated by CMS, you can either use .live() or you can add the click handler in your $('#myLink').click() function
Like so:
$('#myLink').click(function(event) {
event.preventDefault();
$('<div id="iContainer">Test: <input type="text" value="" id="test_text" />
<input type="button" id="test_button" value="click" /></div>').appendTo('body');
$("#iContainer").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#iContainer").remove();
}
});
$('#test_button').click(function() {
alert('I am in Alert');
//alert($('#test_text').val());
});
});

Categories