OnFocusOut not working when UL loses focus - javascript

I need your help,
I can't seem, for the life of me, be able to figure as to why I cannot set the $("#fileno_list").css("display", "none"); Ie. when the user hasn't quite made a selection and decides to click elsewhere on the page. Then the dropdown box should close. (display: none).
Here's a picture of the problem:
Here's the code in Question:
<script type="text/javascript">
$(document).ready(function() {
$("#fileno_list ul").focusout(function() {
$(this).css("display", "none");
});
});
function test() {
var rs_count = 3
if (rs_count > 1) {
for (var x = 0; x < rs_count; ++x) {
$("#fileno_list").append('<li>'+x+'</li>');
}
$("#fileno_arrow").css("display", "block");
}
$("#fileno_arrow").click(function() {
$("#fileno_list").css("display", "block");
});
$("#fileno_list li").click(function(e) {
var select = $(this).closest('#fileno_list')
select.find(".selected").removeClass('selected');
$(this).addClass('selected');
$("#fileno").val( $.trim( $(this).html() ) )
$("#fileno_list").css("display", "none");
});
$("#fileno").val( $("#fileno_list li").eq(0).html() )
}
</script>
Here is the HTML Markup:
<div class="field_container">
<div class="field_wrapper"><input type="text" class="field" id="fileno"></div>
<div id="fileno_arrow"></div>
<ul id="fileno_list"></ul>
</div>
<br>
<br>
<input type="button" onclick="test()" value="click me">
<br>

Assuming your select tag has an id, you can use event object to check which element was clicked and show/hide based on that.
$(document).click(function(e) {
if(e.target.id === "idOfSelect")
$("#idOfSelect").show();
});

Related

jQuery - Hiding One Div & Showing Multiple Other Divs

http://jsfiddle.net/cEJtA/
$(function () {
$(".div1, .div2").hide();
$(".link1, .link2").bind("click", function () {
$(".div1, .div2").hide();
if ($(this).attr("class") == "link1")
{
$(".div1").show();
}
else
{
$(".div2").show();
}
});
});
Can anyone please help with this code.
I want 5 divs that work based on the link that's clicked, so there are 5 divs either shown/hidden.
I can do everything except the if/else statement for more divs - any help please?
Off the top of my head, you can add a data attribute on the class and use that to toggle the targeted div element.
$(function () {
$(".div1, .div2,.div4, .div3, .div5").hide();
$("a").bind("click", function () {
$(".div1, .div2,.div4, .div3, .div5").hide();
var target = $(this).data("target");
$("."+target).toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Link 1
Link 2
Link 3
Link 4
Link 5
<div class="div1">I'm div1</div>
<div class="div2">I'm div2</div>
<div class="div3">I'm div3</div>
<div class="div4">I'm div4</div>
<div class="div5">I'm div5</div>
</body>
</html>
you could also get the current element's class, parse it and generate div class name off of it and use that to show/hide things. e-g
link1 => div1 (replace link with div)
Try this way
<html>
<body>
Link 1
Link 2
<div id="link1" class="commonDiv">I'm div1</div>
<div id="link2" class="commonDiv">I'm div2</div>
</body>
</html>
$(function () {
$(".commonDiv").hide();
$(".link1, .link2").bind("click", function () {
$(".commonDiv").hide();
var id = $(this).attr("class");
$('#' + id).show();
});
});

Add class in parent div

<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
I'm trying to add a class in a div only if the input field has value.
I mean if we put text in input field the div automatically should add a class it's self. Bu the only problem is we can't give any class name or Id
to input.
Using this script about we can add class when we click on input. But we need to do more.
Can we do that?
You can use input instead of focus. You also have to check the value to add/remove the class. Try the following way:
$(document).ready(function(){
$('.parent > *').focus();
$('.parent > *')
.on('input', function() {
if($(this).val().trim() != '')
$(this).parent().addClass('focused');
else
$(this).parent().removeClass('focused');
});
});
.focused{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">Test <input type="text" /> </div>
Sure, just use .parent > input:
$('.parent > input')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
With the html you provided, this should work
$('.parent > *')
.focus(function() {
if( $(this).val().length) $(this).parent().addClass('focused');
})
.blur(function() {
if( $(this).val().length) $(this).parent().removeClass('focused');
});
Update after OP comment
<div class="some-div">Hello</div>
<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$(".some-div").addClass('focused');
})
.blur(function() {
$('.some-div').removeClass('focused');
});
How about putting a event-listener on the input field.
If the input box goes empty, remove the class. Otherwise, add the required class.
Closest helps you find the closest member with the given selection criteria.
For each element in the set, get the first element that matches the
selector by testing the element itself and traversing up through its
ancestors in the DOM tree.
$('input').change(function(){
if( $(this).val().trim() === '' ){//Empty input box
$(this).closest('.parent').removeClass('focused');
}
else{
$(this).closest('.parent').addClass('focused');
}
}
);
Here input event fires on Keyboard input, Mouse Drag, Autofill, and Copy-Paste.
You can try below code -
function toggleParentClass(elem) {
console.log(elem.val());
if (elem.val().length)
elem.closest('.parent').addClass('focused');
else
elem.closest('.parent').removeClass('focused');
}
$('.parent').on('input', function() {
toggleParentClass($(this).find('input'));
});
.focused {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="text" />
</div>

Better way to write jquery add/remove class

I'm not an expert on JS and jQuery, but I would like to improve my knowledge.
I made this code that works for me, but I'm sure it can be done better. can you help me and explain how to synthesize it?
It's a piece of a slideshow when a URL is activated via a button, some images disappear and another appears.
<script>
$(".green").click(function(e){
window.location = "#img_green";
$('#piz_green').css("display", "block");
$('#piz_army').css("display", "none");
$('#piz_red').css("display", "none");
$('#piz_white').css("display", "none");
$('#piz_blue').css("display", "none");
$('#piz_black').css("display", "none");
});
$(".army").click(function(e){
window.location = "#img_army";
$('#piz_green').css("display", "none");
$('#piz_army').css("display", "block");
$('#piz_red').css("display", "none");
$('#piz_white').css("display", "none");
$('#piz_blue').css("display", "none");
$('#piz_black').css("display", "none");
});
$(".red").click(function(e){
window.location = "#img_red";
$('#piz_green').css("display", "none");
$('#piz_army').css("display", "none");
$('#piz_red').css("display", "block");
$('#piz_white').css("display", "none");
$('#piz_blue').css("display", "none");
$('#piz_black').css("display", "none");
});
$(".white").click(function(e){
window.location = "#img_white";
$('#piz_green').css("display", "none");
$('#piz_army').css("display", "none");
$('#piz_red').css("display", "none");
$('#piz_white').css("display", "block");
$('#piz_blue').css("display", "none");
$('#piz_black').css("display", "none");
});
$(".blue").click(function(e){
window.location = "#img_blue";
$('#piz_green').css("display", "none");
$('#piz_army').css("display", "none");
$('#piz_red').css("display", "none");
$('#piz_white').css("display", "none");
$('#piz_blue').css("display", "block");
$('#piz_black').css("display", "none");
});
$(".black").click(function(e){
window.location = "#img_black";
$('#piz_green').css("display", "none");
$('#piz_army').css("display", "none");
$('#piz_red').css("display", "none");
$('#piz_white').css("display", "none");
$('#piz_blue').css("display", "none");
$('#piz_black').css("display", "block");
});
</script>
Thank you.
To improve this code we also can improve html a little. We can add some class to identify elements and controls and after that - we might need only 6 lines of js
Please try this
$(".your-button-class").click(function(e) {
const color = e.target.dataset.color;
window.location = "#img_" + color;
$('.your-div-class').css("display", "none");
$('div[data-color=' + color + ']').css("display", "block");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="your-button-class" data-color="green">green</button>
<button class="your-button-class" data-color="army">army</button>
<button class="your-button-class" data-color="red">red</button>
<button class="your-button-class" data-color="white">white</button>
<button class="your-button-class" data-color="blue">blue</button>
<button class="your-button-class" data-color="black">black</button>
</div>
<div class="your-div-class" data-color="green">green</div>
<div class="your-div-class" data-color="army">army</div>
<div class="your-div-class" data-color="red">red</div>
<div class="your-div-class" data-color="white">white</div>
<div class="your-div-class" data-color="blue">blue</div>
<div class="your-div-class" data-color="black">black</div>
There is no need for JavaScript here as you can do that with basic CSS as follows.
Use proper links with anchors:
green
<!-- repeat for other colors -->
black
Then use the :target pseudo-class as follows:
#piz_green,
#piz_army,
#piz_red,
#piz_white,
#piz_blue,
#piz_black {
display: none;
}
#piz_green:target,
#piz_army:target,
#piz_red:target,
#piz_white:target,
#piz_blue:target,
#piz_black:target {
display: block;
}
And by adding a parent element, you can simplify it as follows:
#container > * {
display: none;
}
#container > *:target {
display: block;
}
Data attributes on the elements and a common class would make your life easier
var slides = $(".slide"); // reference all the slides
$("[data-action").on("click", function(e){ // bind the click
var btn = $(this); // button that was clicked
var color = btn.data("action"); // get the color
slides.attr("hidden", true); // hide all the slides
$("#piz_" + color).removeAttr("hidden"); // show the clicked color
window.location.hash = "img_" + color; // update the hash
});
[hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-action="green">Green</button>
<button data-action="red">Red</button>
<button data-action="blue">Blue</button>
<div class="slide_wrapper">
<div class="slide" id="piz_green">green</div>
<div class="slide" id="piz_red">red</div>
<div class="slide" id="piz_blue">blue</div>
</div>
function slideshow(image_id, block_id){
window.location = image_id;
$("[id^=piz_]").css("display", "none");
$(block_id).css("display", "block");
}
$(".green").click(function(e){
slideshow("#img_green", "#piz_green");
});
Here is the solution I would go with. First I would add an arbitrary data attribute, in this case, colour. Then I would add all my buttons with a corresponding data attribute. Then attach to the click event of those buttons and call the following code.
$('[data-action=toggle]').click(function(e){
$('div[data-color]:not([data-color=' + e.target.dataset.color + '])').hide();
$('div[data-color=' + e.target.dataset.color + ']').show();
})
a{
margin-right: .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="green">green</div>
<div data-color="red">red</div>
<div data-color="blue">blue</div>
<div data-color="pink">pink</div>
<div data-color="yellow">yellow</div>
Green
Red
Blue
Pink
Yellow
When I highly suggest the use of common classes in this case, you could always use comma , separator in you selectors with show()/hide() to simplify your code (a little) like :
$(".green").click(function(e) {
window.location = "#img_green";
$('#piz_green').show();
$('#piz_army,#piz_red,#piz_white,#piz_blue,#piz_black').hide();
});
$(".army").click(function(e) {
window.location = "#img_army";
$('#piz_army').show();
$('#piz_green,#piz_red,#piz_white,#piz_blue,#piz_black').hide();
});
$(".red").click(function(e) {
window.location = "#img_red";
$('#piz_red').show();
$('#piz_green,#piz_army,#piz_white,#piz_blue,#piz_black').hide();
});
$(".white").click(function(e) {
window.location = "#img_white";
$('#piz_white').show();
$('#piz_green,#piz_army,#piz_red,#piz_blue,#piz_black').hide();
});
$(".blue").click(function(e) {
window.location = "#img_blue";
$('#piz_blue').show();
$('#piz_green,#piz_army,#piz_red,#piz_white,#piz_black').hide();
});
$(".black").click(function(e) {
window.location = "#img_black";
$('#piz_black').show();
$('#piz_green,#piz_army,#piz_red,#piz_white,#piz_blue').hide();
});
Another suggestion with no need to change your HTML structure:
$(".green, .army, .red, .white, .blue, .black").click(function(e) {
var color = $(this).prop('class');
window.location = "#img_" + color;
$('[id^=piz_]').hide();
$('#piz_' + color).show();
});
You can consider attribute selector to hide all the element at once. Make sure to call hide() before show()
$(".green").click(function(e) {
window.location = "#img_green";
$('[id^=piz]').hide();
$('#piz_green').show();
});
$(".army").click(function(e) {
window.location = "#img_army";
$('[id^=piz]').hide();
$('#piz_army').show();
});
$(".red").click(function(e) {
window.location = "#img_red";
$('[id^=piz]').hide();
$('#piz_red').show();
});
$(".white").click(function(e) {
window.location = "#img_white";
$('[id^=piz]').hide();
$('#piz_white').show();
});
$(".blue").click(function(e) {
window.location = "#img_blue";
$('[id^=piz]').hide();
$('#piz_blue').show();
});
$(".black").click(function(e) {
window.location = "#img_black";
$('[id^=piz]').hide();
$('#piz_black').show();
});
You can store id of the image you want to show as custom data attribute with each button and then hide all images (by giving them a common class) with one line and show only the image you need by it's id from custom data attribute.
Example of button element:
<button data-slideshow-button="green">Green</button>
Example of slideshow element:
<div id="piz_green" class="slideshow-image"></div>
And then just run code like this as click handler:
$('[data-slideshow-button]').click(function(e){
var showId = $(e.currentTarget).data('slideshowButton');
window.location = '#img_' + showId;
$('.slideshow-image').hide();
$('#piz_' + showId).show();
});
As you did use piz_ for all classes in your HTML, you can easily use them in your JavaScript. For example, if you want to hide them all you can just type:
$('[class^=piz_]').hide();. This will hide all elements where the class starts with piz_.
Now I made a quick example with this in action. Please know I made just tile and a retry button to give you an example.
$("[class^=piz_]").click(function(){ // Make all div's with the class piz_* clickable
$('[class^=piz_]').hide(); // Hide all elements
var classAttr = '.'+$(this).attr("class"); // Get the class from the tile you clicked on
$(classAttr).show(); // Show all tiles with the same class
});
// This is just to get all tiles back and try it again.
$('.retry').click(function() {
$('[class^=piz_]').show();
});
.piz_green { background:green; }
.piz_blue { background:blue; }
.piz_red { background:red; }
.piz_orange { background:orange; }
div, button { width:100px; height:100px; }
.retry { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="piz_green"></div>
<div class="piz_blue"></div>
<div class="piz_red"></div>
<div class="piz_orange"></div>
<div class="piz_green"></div>
<button class="retry">
Retry!
</button>

how do I add a click attribute to a DIV without it applying to elements inside it?

I have a DIV that when clicked on expands to reveal some inputs and buttons, and will close when clicked on again, hiding those elements. The problem I am having is that when I click on the buttons or the input boxes the closing animation happens anyway. I know I can solve this by taking the inputs and buttons out of the DIV but the DIV is very important for their formatting and organization. Any help would be great, thanks!
html:
<div id='inputArea1' class='inputAreas'>
<input id='email' class='evInput' placeholder='example#gmail.com'>
<input id='comf' class='evInput' placeholder='Comfirmation Code'>
<button id='sndCde' class='evBut'>Send Code</button>
<button id='comfBut' class='evBut'>Comfirm</button>
</div>
JS:
var main = function() {
$('.box').click(function() {
var el = $(this);
if (!el.hasClass('selected')) {
el.animate({
"height": "300px"
}, 200)
el.addClass("selected");
el.find('.inputAreas').show();
} else {
el.animate({
"height": "85px"
}, 200);
el.find('.inputAreas').hide();
el.removeClass("selected");
}
})
}
$(document).ready(main);
FULL CODE: https://jsfiddle.net/dL2vzga0/
event.stopPropagation(); can do the job:
$('#inputArea1').click(function(event){
event.stopPropagation();
});
Fixed Fiddle

To do list jquery, cross out item

I"m making a very simple to-do list with jquery. I have an input box for adding thing and once entered it will print out that underneath:
HTML:
<html>
<head>
<title>My to-do list</title>
<link rel="stylesheet" href="css/list.css" >
</head>
<body>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="js/list.js"></script>
<div id="empty-top"></div>
<div align= "center" class="wrapper">
<h2>Add thing to your to-do list</h2>
<input id='input' type="text" placeholder="To-do-list" >
</div>
<div class = "things">
</div>
</body>
</html>
my js file:
$(function(){
$("#input").keypress(function(e){
if(e.which == 13){
var content = $("#input").val();
$("<li>" + content + "<input id= 'check' type='checkbox'> </li>").appendTo(".things");
};
});
//I want to check if the box is checked. If it is then I want to insert the tag to cross that item. This function, however does not work. I also tried ("input").is(":checked") or ("input").prop("checked",true) but still doesn't do what I wanted.
$("#check").click(function(){
var box = $(this);
$("<del>").insertBefore("<li>");
$("</del>").insertAfter("</li>");
});
});
Thank you!!!!!!!!
Firstly, you can't append LI elements to a DIV, it should be an UL or OL parent element, and you can't wrap the LI in a DEL, as a DEL element can't be a child of an UL, so you have to wrap the inner element, and unwrap it when the checkbox is unchecked again.
As for the event handler, you can attach that when you create the element, and you should be listening to the change event etc.
$(function () {
$("#input").keypress(function (e) {
if (e.which == 13) {
var content = $("#input").val();
var li = $('<li />', {
text : this.value
}),
inp = $('<input />', {
'class': 'check',
type : 'checkbox',
on : {
change: function() {
if (this.checked) {
$(this).closest('li').wrapInner('<del />');
}else{
$(this).unwrap();
}
}
}
});
$('.things').append( li.append(inp) );
};
});
});
FIDDLE
To see if your checkbox is checked, you can use:
$("input").get(0).checked
I would suggest adding a class in your CSS:
.complete{text-decoration:line-through}
And then add the complete class if checked
if($("input").get(0).checked){
$('corresponding-list-item').addClass('complete');
}

Categories