javascript change event behavior - javascript

Can someone explain to me the behavior of change event in my javascript code? I have two event-listeners attached to the search input box so when the value of input changed it print the changed value; when input box is clicked it empties the value.
My question is when I click the search box the value of input box changed from something to empty, so why doesn't it trigger change event?
var search = document.querySelector("#search");
search.addEventListener("change",function(){
console.log("change event occur");
console.log($("#search").val());
})
var search = document.querySelector("#search");
search.addEventListener("click",function(){
console.log("click event occur");
$("#search").val(' ');
})
body,html{
background-color:#092B40;
width: 100%;
height: 100%;
border-color: transparent;
margin:0;
padding:0;
}
.entry{
display: block;
background-color: #F8ECC2;
margin-top: 10px;
border-radius: 3px;
min-width:600px;
height:90px;
width: 100%;
}
.container{
overflow:hidden;
}
#search{
display:inline-block;
width:50%;
}
#wiki{
margin-top: 0%;
animation: 2s slide-up;
}
#keyframes slide-up{
from{
margin-top:100%;
opacity:0;
}
to{
margin-top:0%;
opacity:1;
}
}
<head>
<title>Wiki Search API</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="main.css" type="text/css" />
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous">
</script>
</head>
<body>
<div class='container'>
<div id='search-box' class="form-group text-center">
<input id='search' type="text" class="form-control" placeholder="Search for...">
<submit id='go-button' class='btn btn-info '>Go!</submit>
<button id='random' class='btn btn-warning '><a href='https://en.wikipedia.org/wiki/Special:Random'>Random!</a></button>
</div>
<!--<div class='filler well'>-->
<!--</div>-->
<div id='wiki' class='row'>
<a class="entry">
<p>Hello</p>
</a>
<a class="entry">
<p>Hello</p>
</a>
<a class="entry">
<p>Hello</p>
</a>
<a class="entry">
<p>Hello</p>
</a>
<a class="entry">
<p>Hello</p>
</a>
<a class="entry">
<p>Hello</p>
</a>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>

It's because events are only raised from user input. Programmatically changing the value of an input doesn't raise an event. If you want one to occur, then you need to trigger() it manually, like this:
var search = document.querySelector("#search");
search.addEventListener("click", function(){
console.log("click event occur");
$("#search").val('').trigger('change');
})
Also note that you're using an odd mix of plain JS and jQuery. It's better practice to stick to one or the other. As you've loaded jQuery, you may as well use it:
$(function() {
$('#search').on({
change: function() {
console.log("change event occur");
console.log($(this).val());
},
click: function() {
console.log("click event occur");
$(this).val('').trigger('change');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id='search' type="text" class="form-control" placeholder="Search for...">

I usually dont use change event with text or text-area input. I use propertychange
var search = document.querySelector("#search");
search.addEventListener("propertychange ",function(){
console.log("change event occur");
console.log($("#search").val());
});
Or with jquery you can use propertychange event like this:
$("#search").bind('input propertychange', function(){
console.log("change event occur");
console.log($("#search").val());
});

When the placeholder is removed from the search input that is not changing the value of the text box, it is only hiding the placeholder.

Related

jQuery - hidden class is not being displayed with fadeIn

I have a hidden class fadeThis, which does not appear when I hover over the button.
Perhaps it is clashing with another class/div?
What I'm essentially trying to do is create a red fade in over the grey box, when the cursor hovers over the button, and then when the cursor leaves the box(not the button), I want it to return back to it's original state.
I've also added the CSS to help demonstrate
HTML
<div class="imageOne">
<div class="onClickThis"> <!-- hidden by default-->
<h2 class="fadeThis">Whatever the text needs to be</h2> <!-- hidden by default-->
</div>
<div class="centerButton">
<button class="btn">View More</button>
</div>
</div>
CSS
.imageOne{
height: 300px;
width: 400px;
background-color: grey;
}
.centerButton{
display: flex;
justify-content:center;
padding-top:150px;
}
.btn{
height: 30px;
width:170px;
}
.onClickThis{
height: 300px;
width: 400px;
background-color: tomato;
}
JavaScript
$(document).ready(function () {
$(".onClickThis").hide();
$(".fadeThis").hide();
$(".btn").hover(function () {
$(".imageOne").fadeIn("slow", function () {
$(this).addClass("fadeThis onClickThis");
$(".btn").remove();
});
$(".onClickThis").mouseleave(function () {
$(this).removeClass("fadeThis onClickThis");
});
});
});
I don't understand exactly what you are looking for. Maybe you could provide more details.
Here is a demo started from your code with some changes added.
$(document).ready(function () {
$(".onClickThis, .fadeThis").hide();
$(".btn").hover(function () {
$(".imageOne").fadeIn("slow", function () {
$(".onClickThis, .fadeThis").fadeIn( 250 );
$(".btn").fadeOut();
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="imageOne">
<div class="onClickThis"> <!-- hidden by default-->
<h2 class="fadeThis">Whatever the text needs to be</h2> <!-- hidden by default-->
</div>
<div class="centerButton">
<button class="btn">View More</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>

How do I loop through HTML elements while executing a function on each element

I am a newbie to Javascript, I wanted to implement a for loop that would go through each div as selected by its class.
The simple idea is to reveal DIVs when I click on a button. But it has to be sequential: I click DIV1 appears, when I click again DIV2 appears and so on. Currently my code only changes the class of one DIV and not the rest. Here are my code samples:
$(document).ready(function(){
// jQuery methods go here...
var count = document.getElementById("page1").childElementCount;
for(var i = 0; i < count; i++){
var myClass = ".panel" + i;
$("button").click(function(){
$(myClass).addClass("showing animated fadeIn")
});
}
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
Please let me know what I am missing especially in the for loop or if I can do something else to be able to grab a DIV and add a class every time I click on the button.
Firstly, the HTML attribute class is made for multiple elements with the same style/behaviour. You should use id if it is to dissociate one panel for another.
You have to store a count variable to know which panel has to appear next.
And always try to do what you want in Javascript without jQuery if it is possible !
var i = 1;
function clickBtn() {
if (!document.getElementById("panel-" + i))
return;
document.getElementById("panel-" + i).classList.add("visible");
i++;
}
.panel {
width: 50px;
height: 50px;
display: none;
margin: 5px;
background-color: #bbb;
}
.panel.visible {
display: block;
}
<button onclick="clickBtn()">click me</button>
<div>
<div id="panel-1" class="panel"></div>
<div id="panel-2" class="panel"></div>
<div id="panel-3" class="panel"></div>
<div id="panel-4" class="panel"></div>
</div>
You could use counter like clickCount instead of for loop
$(document).ready(function(){
// jQuery methods go here...
var clickCount = 1;
$("button").click(function(){
var myClass = ".panel" + clickCount;
$(myClass).addClass("showing animated fadeIn")
clickCount++;
});
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
You've got this a little bit backwards; you're trying to attach an event handler to the button for each element. Instead, you should have one event handler for the button, which cycles through the elements.
You could set a variable to keep track of which element is currently highlit, but it's easier to just determine that based on the current state of the DOM:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.removeClass('showing') // clear it
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
There's a small cheat in the above -- if the current element is the last one, then it won't have a next() to highlight. That's why I waited to check for the case where there's nothing visible until after moving the highlight; that way it will work for both the first click, and for when you need the highlight to loop back around to the first element.
If you intended to have the elements reveal themselves in sequence and not hide earlier ones, just get rid of the .removeClass('showing') line:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
What you can do is count the amount of children that you have, and compare the amount of clicks through a given iterator you have to see what should be shown.
I added an extra functionality that hides the elements again once the max amount of divs has been shown.
Hope this helps.
$(document).ready(function() {
$('#page1').children().each(function () {
$(this).hide();
});
});
var panel="panel";
var pannelNum=0;
var count = $("#page1").children().length;
$(".one").on( "click", function() {
pannelNum=pannelNum+1;
if(pannelNum > count) {
$('#page1').children().each(function () {
$(this).hide();
});
pannelNum=0;
}
else {
clicked=panel+""+pannelNum;
$('.'+clicked).show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
this is panel 1!
</div>
<div class="panel2">
this is panel 2!
</div>
<div class="panel3">
this is panel 3!
</div>
<div class="panel4">
this is panel 4!
</div>
</div><!-- page one -->
<div id="trial">
</div>

How to add Animation in toggleClass functon in Jquery

I am making a div which would show on button click and hide on clicking again.I am using toggleClass function of jquery. The problem is I need animation while the div opens and closes. I have tried transition:1s, in all relevant classes and even on body, but in vain.
This is the fiddle: http://jsfiddle.net/9dq2p7dw/105/
Here is the code for my jquery:
$(document).ready(function(){
$(".view").click(function(){
$(".view-more").toggleClass("hide show", 500);
});
});
You can use .fadeToggle
$(document).ready(function(){
$(".view").click(function(){
$(".view-more").fadeToggle( "hide show", "linear" );
});
});
.hide{
display:none;
}
.show{
display:block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="view">View All</a>
<div class="view-more hide" >
<div class="col-md-6">
<h1>
asasasas
</h1>
</div>
<div class="col-md-6">
<h1>
sasasas
</h1>
</div>
</div>
Use transition: all 0.3s ease;
Refer CSS transitions
$(document).ready(function() {
$(".view").click(function() {
$(".view-more").toggleClass("hide show", 500);
});
});
.hide {
opacity: 0;
transition: all 1s ease;
}
.show {
opacity: 1;
transition: all 1s ease;
}
.view-more{
background-color:#F0C798;
padding:10px;
box-sizing:border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="view">View All</a>
<div class="view-more hide">
<div class="col-md-6">
<h1>
asasasas
</h1>
</div>
<div class="col-md-6">
<h1>
sasasas
</h1>
</div>
</div>
JS Fiddle Link
If all you wish to do is hide and show a div upon clicking a button, you can do so in simpler way.
$(".view").click(function(){
$(".view-more").toggle(function() {
$(this).animate({height: '200'});
}, function() {
$(this).animate({height: '100'});
});​
});
When given a list of functions as arguments, the .toggle(fn1, fn2) method will alternate between the functions given starting with the first one. This automatically keeps track of the toggle state for you - you don't have to do that.
jQuery doc is here. There are multiple forms of .toggle() depending upon the arguments used so you don't always find the right one when searching the jQuery doc.
try this, You can't animate display, rather try this, may be this will help you
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<style>
.col-md-6{
background:red;
}
</style>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<a class="view">View All</a>
<div class="view-more hide" >
<div class="col-md-6">
<h1>
asasasas
</h1>
</div>
<div class="col-md-6">
<h1>
sasasas
</h1>
</div>
</div>
<script>
$(document).ready(function(){
$(".view").click(function(){
$(".view-more").toggle(500);
});
});
</script>
</body>
</html>

How to change image to text using jquery's .hover event

I need a simple script that allows me to change the inner html of a p tag which in my case is an image to just plain text when I hover over it.
Example:
<div id="one">
<p><img src="events.png" alt="" /></p>
</div>
When i hover over the above p tag i want it to change to the text as seen below
<div id="one">
<p>Events</p>
</div>
You don't need to use javascript at all for this. This is handled very simply using css.
<div id="one">
<p>
<span>Events</span>
<img src="events.png" alt="" />
</p>
</div>
CSS:
#one p>span{ display:none; }
#one p:hover span{ display:inline; }
#one p:hover img{ display:none; }
Here's a fiddle of it in action: http://jsfiddle.net/CKpCk/
Try the following:
var html = $('#one p').html()
$('#one').hover(function(){
$('p', this).html('Events');
}, function() {
$('p', this).html(html);
})​
Demo
Try this one:
<html>
<head>
<title>Try</title>
</head>
<script type="application/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#testHover").hover(function()
{
$("#testHover").html("Events");
});
});
</script>
<body>
<div id="one">
<p style="width:200px;"id="testHover"><img src="events.jpg" alt="" /></p>
</div>
</body>
</html>

Setting focus on an HTML input box on page load

I'm trying to set the default focus on an input box when the page loads (example: google).
My page is very simple, yet I can't figure out how to do this.
This is what I've got so far:
<html>
<head>
<title>Password Protected Page</title>
<script type="text/javascript">
function FocusOnInput()
{
document.getElementById("PasswordInput").focus();
}
</script>
<style type="text/css" media="screen">
body, html {height: 100%; padding: 0px; margin: 0px;}
#outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
#middle {vertical-align: middle}
#centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
</style>
</head>
<body onload="FocusOnInput()">
<table id="outer" cellpadding="0" cellspacing="0">
<tr><td id="middle">
<div id="centered">
<form action="verify.php" method="post">
<input type="password" name="PasswordInput"/>
</form>
</div>
</td></tr>
</table>
</body>
</html>
How come that doesn't work while this works fine?
<html>
<head>
<script type="text/javascript">
function FocusOnInput()
{
document.getElementById("InputID").focus();
}
</script>
</head>
<body onload="FocusOnInput()">
<form>
<input type="text" id="InputID">
</form>
</body>
</html>
Help is much appreciated :-)
And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.
<input type="text" name="fname" autofocus>
This line:
<input type="password" name="PasswordInput"/>
should have an id attribute, like so:
<input type="password" name="PasswordInput" id="PasswordInput"/>
This is one of the common issues with IE and fix for this is simple.
Add .focus() twice to the input.
Fix :-
function FocusOnInput() {
var element = document.getElementById('txtContactMobileNo');
element.focus();
setTimeout(function () { element.focus(); }, 1);
}
And call FocusOnInput() on $(document).ready(function () {.....};
You could also use:
<body onload="focusOnInput()">
<form name="passwordForm" action="verify.php" method="post">
<input name="passwordInput" type="password" />
</form>
</body>
And then in your JavaScript:
function focusOnInput() {
document.forms["passwordForm"]["passwordInput"].focus();
}

Categories

Resources