checking if a div is empty and ignoring white spaces - javascript

I need to check if a div is empty and ignore white spaces.
If you type one or more spaces inside the below div and click the button, it logs "empty" instead of "not empty".
$('button').on('click', function(){
let a = $('#wrap').html();
if(a == '' || a.trim() == ''){console.log('empty');}
else{console.log('not empty');}
});
.wrap{
background:gold;
min-height:25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

You should use .text() instead. Also, the first check for an empty string is superfluous. The root cause of this issue is that spaces are represented as in HTML, which you can see if you console.log(a).
$('button').on('click', function() {
let a = $('#wrap').text();
if (a.trim() == '') {//or simply, if(!a.trim()){
console.log('empty');
} else {
console.log('not empty');
}
});
.wrap {
background: gold;
min-height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

You can simply jQuery .text() to check for length of any text in div. This will avoid (not count) spaces.
The way .html() works is that it will count white spaces as well.
Run snippet below.
$('button').on('click', function() {
let a = $('#wrap').text();
if (a == '' || a.trim() == '') {
console.log('empty');
} else {
console.log('not empty');
}
});
.wrap {
background: gold;
min-height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

Related

Change div css if span contain text

I have one input and span. When I type in input value is passed to span. Now I want to hide other div/button or something if my span have specific value. My code don't work. What's wrong?
$('#input').on('keyup', function(){
$('#status').html($(this).val());
});
$('#status').on('change', function(){
var status = $('#status').html();
if (status == "OK") {
$('#test').css("background", "red");
} else {
$('#test').css("background", "blue");
}
});
#test {
width: 50px;
height: 50px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">
<span id="status"></span>
<div id="test"></div>
Instead of checking changes on span element, it is better to do this logic inside of input event listener. Something like this:
$('#input').on('keyup', function(){
var val = this.value;
$('#status').html(val);
if (val == "OK") {
$('#test').css("background", "red");
} else {
$('#test').css("background", "blue");
}
});
Liste the keyup event and change the background
$('#input').on('keyup', function(){
$('#status').html($(this).val());
console.log($(this).val());
if ($('#status').html() == "OK") {
$('#test').css("background", "red");
} else {
$('#test').css("background", "blue");
}
});
#test {
width: 50px;
height: 50px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">
<span id="status"></span>
<div id="test-container">
<div id="test"></div>
</div>

Showing a div and keep it show() if i clicked on it

$(document).ready(function() {
$('#input').focusin(function() {
if ($(this).val() != '') {
$('#div').show();
} else {
$('#div').hide();
}
$('#input').keyup(function() {
// If not empty value, show div
if ($(this).val() != '') {
$('#div').show();
} else {
$('#div').hide();
}
});
});
$('#input').focusout(function() {
$('#div').hide();
});
});
#div {
display: none;
position: absolute;
bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
<a href='website.com'>Link From AJAX<a>
<a href='website.com'>Link From AJAX<a>
<a href='website.com'>Link From AJAX<a>
</div>
<input id='input' type='text'>
In this jquery code, the #div shows when i type something inside the #input but if i tried to click on the #div it disappears and the link doesn't work,
How can i keep the #div shown if i clicked on #div or #input only, But anything outside will hide it as normal?
The Problem happens because of position: absolute; bottom 20px line in CSS.
Updated the code and suddenly it worked as intended after adding if statement after .focusin function, For previous error solution, remove the position and bottom in the CSS
You could disable the effect of the focusout handler by the use of a flag:
var noHide = false;
$(document).ready(function() {
$('#input').keyup(function() {
// If not empty value, show div
if ($(this).val() != '') {
$('#div').show();
} else {
$('#div').hide();
}
});
$('#div a').hover(
function() { noHide = true; },
function() { noHide = false; $('#input').focus(); }
);
$('#input').focusout(function() {
if(!noHide) {
$('#div').hide();
}
});
});
#div {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
<a href='#'>HellWorld</a>
</div>
<input id='input' type='text'>
When you blur out of the input, check if the currently active element is the DIV, and hide it if it isn't.
Also, if you're positioning an element absolutely, you need to give it a z-index so you can click on it. Otherwise, the click is sent to the normally-positioned element at that location.
$(document).ready(function() {
$('#input').focus(function() {
if ($(this).val() != '') {
$('#div').show();
} else {
$('#div').hide();
}
}).blur(function() {
if (!$("#div").is(":focus,:active")) {
$("#div").hide();
}
});
$('#input').keyup(function() {
// If not empty value, show div
if ($(this).val() != '') {
$('#div').show();
} else {
$('#div').hide();
}
var search = $('#input').val();
$.post('search.php', {
search: search
}, function(data) {
$('#div').html(data);
});
});
});
#div {
display: none;
position: absolute;
bottom: 20px;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
<a href='www.someplace.com'>HellWorld</a>
</div>
<input id='input' type='text'>

Remove (and Add) Classes to HTML Element with jQuery, While Updating the DOM tree

I'm trying to change a div's attribute class. I have three defined classes and want to cycle through the classes when a user initiates a click event. The first click event works as expected, but the second doesn't show any results.
I've went through a few iterations of trying to get this to work, but have not had any success. I think what's going on is that the DOM tree isn't being updated with the click event, so when the second click event is fired it sees the card-green class, adds the card-yellow class and then exits the branching logic.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[0]);
}
})
});
Use a switch and toggleClass(). Details are commented in Snippet. No need for an array if you are using a limited number of options. When using $(this) you don't need to keep track of what you clicked (much like event.target except $(this) isn't concerned about events as it is concerned with owner of function.)
SNIPPET
$(document).ready(function() {
$(document).on('click', 'div', function(event) {
/* Determine $(this) class
|| Pass class through the switch
*/
var color = $(this).attr('class');
/* Each part of the switch is a if/else
|| conditional. If the condition isn't
|| met, then it will kick you
|| down to the next conditional and
|| so on, until you reach default or
|| meet a condition in which case the
|| break will kick you out of switch.
|| Each condition has a toggleClass()
|| method to switch colors according
|| to the present class of div
*/
switch (color) {
case 'green':
$(this).toggleClass('green yellow');
break;
case 'yellow':
$(this).toggleClass('yellow red');
break;
case 'red':
$(this).toggleClass('red green');
break;
default:
break;
}
});
});
div {
height: 30px;
width: 50px;
border: 1px solid black;
cursor: pointer;
}
.green {
background: green
}
.red {
background: red;
}
.yellow {
background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
This changes the color in order of the cards array when elements within the document body are clicked:
(Very similar to #gyre's answer, only includes the event.target within the code logic, rather than just the body).
var cards = ['card-green', 'card-yellow', 'card-red'];
$('body').on('click', function() {
var elem = event.target,
curClass = $(elem).attr('class'),
i = cards.indexOf($(elem).attr('class'));
$(elem)
.removeClass(curClass)
.addClass(cards[i = (i + 1) % cards.length]);
});
div {
height: 100px;
width: 100px;
display: inline-block;
}
.card-green {
background-color: green;
}
.card-yellow {
background-color: yellow;
}
.card-red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="card-green"></div>
<div id="bar" class="card-yellow"></div>
<div id="baz" class="card-red"></div>
Use an additional index variable to keep track of the position in the array:
Demo Snippet:
$(document).ready(function() {
var cardColors = ['card-green', 'card-yellow', 'card-red']
var i = 0
$('body').on('click', function() {
$(this)
.removeClass(cardColors[i])
.addClass(cardColors[i = (i + 1) % cardColors.length])
})
})
body {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
}
.card-green { background-color: green; }
.card-yellow { background-color: yellow; }
.card-red { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The same code is workable just remove nodeName from removeClass(event.target.nodeName.className) instead of this use removeClass(event.target.className).
Try this, Its working for me.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
alert(event.target.className)
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[0]);
}
})
});

How to open a box on screen by clicking a link and hide it when clicked outside in JS

My goal is to have #box2 appear when I click on #box1 but when you click on something other than #box2, it will display none and only #box1 will show.
Here are my 2 boxes, they are just 2 styled divs:
var condition;
$(document).click(function() {
if (condition === 'block') {
$(":not(#box2)").click(function() {
$("#box2").hide();
});
}
})
$('#box1').click(function(e) {
$('#box2').css('display', 'block');
condition = 'block';
});
$('#box2').click(function(e) {
$('#box2').css('display', 'none');
condition = 'none';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" style="width: 300px; height: 300px; background-color: red; margin-left: 100px; margin-bottom: 50px; position: absolute;">
</div>
<div id="box2" style="width: 300px; height: 300px; background-color: blue; margin-left: 150px; display: none; position: absolute;">
</div>
This current code works correctly the first time but after that, it wont run again. I am just wondering if there is a reset function or where I am going wrong?
Really what I want to do is make this work on an ipad so when the user clicks/taps away from the box, it will close. If there are better ways to do this on the Ipad tablet, please let me know!!
Any ideas?
Don't overcomplicate things. This is all the javascript you need, get rid of everything else:
$(document).click(function () {
$('#box2').hide();
});
$('#box1').click(function (e) {
e.stopPropagation();
$('#box2').show();
});
You could just filter event target at document level:
$(document).on('click', function(e) {
$('#box2').toggle(!!$(e.target).closest('#box1').length);
});
-jsFiddle-
You can listen to all click events of the document and then use the event.target to detect which element is being clicked. if the clicked element is box1 and box2 is not being shown then display it to the user. in any other condition we can hide the box2 if it's not the element being clicked. here is the vanilla JavaScript code to achieve this:
<html>
<body>
<div id='box1'>BOX ONE</div>
<div id='box2' style="display: none;">BOX TWO</div>
<script>
document.addEventListener('click', function(event) {
var secondBox = document.getElementById('box2')
if(event.target.id === 'box1' && secondBox.style.display === 'none'){
secondBox.style.display = 'block'
} else if (event.target.id !== 'box2') {
secondBox.style.display = 'none'
}
})
</script>
</body>
</html>
And if you are into DRY (Do not repeat yourself), you can define a function for this task. Take look at this modified version of the script:
function addOpenHandler(handler, target){
document.addEventListener('click', function(event) {
if(event.target === handler && target.style.display === 'none'){
target.style.display = 'block'
} else if (event.target !== target) {
target.style.display = 'none'
}
})
}
addOpenHandler( document.getElementById('box1'), document.getElementById('box2') )
$(document).click(function () {
if (condition === 'block')
{
$(":not(#box2)").click(function () {
$("#box2").hide();
});
}
})
The line $("#box2").hide(); is firing after every click

jQuery: keyup and keydown event

I'm trying to call the keydown and keyup event with JS. Howvever I get a syntax error. What's missing in the code?
HTML:
<body>
<div class="ryu">
<div class="ryu-still"></div>
<div class="ryu-ready"></div>
<div class="ryu-throwing"></div>
</div>
<div class="ryu-cool"></div>
</body>
CSS:
.ryu-cool {
display: none;
background-image: url('http://media-cdn.tripadvisor.com/media/photo-s/03/c5/42/a4/rainbow-spirit.jpg');
}
.ryu-still {
background-image: url('http://media-cdn.tripadvisor.com/media/photo-s/03/c5/42/a4/rainbow- spirit.jpg');
}
JS:
$(document).ready(function(){
$('.ryu').keydown(function(e){
if(e.keyCode == 88){
$('.ryu-still').hide();
$('.ryu-cool').show();
})
.keyup(function(e){
if(e.keyCode == 88){
$('.ryu-still').hide();
$('.ryu-cool').show();
});
});
});
The JSfiddle link: http://jsfiddle.net/3Ppdf/
Along with the code formatting issues other have pointed out, the code still won't function as expected without a small addition.
Working Fiddle
You will need to add a tab index to the <div> element that you want to monitor keyboard input on.
Your HTML should look like this:
<div class="main">
<div tabindex="0" class="ryu">
<div class="ryu-still"></div>
<div class="ryu-ready"></div>
<div class="ryu-cool"></div>
<div class="ryu-throwing"></div>
</div>
</div>
The JavaScript will also need to be updated to:
$(document).ready(function () {
$('.ryu').keydown(function (e) {
if (e.keyCode == 88) {
$('.ryu-still').hide();
$('.ryu-cool').show();
}
})
.keyup(function (e) {
if (e.keyCode == 88) {
$('.ryu-still').show();
$('.ryu-cool').hide();
};
})
});
Also, to get the images to display properly you have to give the <div>s an explicit width and height:
.ryu-cool {
display: none;
background-image: url('http://www.theprojectors.co.uk/img/p/187-219-thickbox.jpg');
width: 600px;
height: 600px;
}
.ryu-still {
background-image: url('http://media-cdn.tripadvisor.com/media/photo-s/03/c5/42/a4/rainbow-spirit.jpg');
width: 550px;
height: 364px;
}
Otherwise the <div>s will have a width and height of zero and therefore not displayed on the page.
You're missing the ending bracket for the if statements. Your code should be this:
$(document).ready(function(){
$('.ryu').keydown(function(e){
if(e.keyCode == 88){
$('.ryu-still').hide();
$('.ryu-cool').show();
}
})
.keyup(function(e){
if(e.keyCode == 88){
$('.ryu-still').hide();
$('.ryu-cool').show();
}
});
});
See updated JSFiddle: http://jsfiddle.net/3Ppdf/3/

Categories

Resources