JS - how to remove setTimeOut for my code - javascript

I am trying to use vertical scroll to display an object A.
The idea is that if my scroll height is greater than scrollHeight (15), then after 1.2 second, A will show up.
Then when I scroll back to top, A will hide.
The problem right now is that if I dont use clearTimeout, the setTimeout will ignore the condition: if ( scroll >= scrollHeight )
When I use clearTimeout, it seems it only works when I scroll very quickly or it just doesnt work.
Here is my code.
var scrollHeight = 15;
$(window).scroll(function() {
var scroll = getCurrentScroll();
var delayThis;
if ( scroll >= scrollHeight ) {
delayThis = setTimeout(function(){
//Display **A**...
}, 1200);
}
else{
// Hide **A** ...
clearTimeout(delayThis);
}
}
Thank you very much for helping!!

You have to tell the script if the message is already showing or not, that way you avoid the multiple delays. Below is a working version of what I'm talking about. I hope that helps.
var scrollHeight = 15;
var message = $( ".message" );
var messagestatus = false;
var scrollposition;
$(window).scroll(function() {
scrollposition = $(document).scrollTop();
if ( scrollposition >= scrollHeight ) {
if ( messagestatus == false ) {
setTimeout(function(){
message.show();
messagestatus = true;
}, 1200);
}
} else{
message.hide();
messagestatus = false;
}
});
.message {
display: none;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>top</p>
<div class="message">
Show!
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br />
<p>bottom</p>

You need to put delayThis outside of the event, up with scrollHeight. Because otherwise it no longer exists. Right now you have it where it is only local to that one scroll event... not the proceeding ones.
Also... you would be setting the timeout over and over as you scroll. So before setting it you probably want to be make sure that delayThis is not already set.

Related

Implementing Scrolling progress bar for more than one element

I'm trying to implement the scrolling progress bar. (The bar that'll tell the user about How much of an article within an div (s)he has read).
Something like implemented on this site.
I've Designed my custom bar and coded it on fiddle. It works fine you can see it.
Here is code:
HTML:
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyz">
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyzprog"><div id="prog">Intro</div></div>
JQuery/JS:
$(function(){
$(window).scroll(function(){
var elemTop=$("#xyz").offset().top,elemHeight=$("#xyz").height();
var total=elemTop+elemHeight;
var scTop=$(window).scrollTop();
var prog=((scTop-elemTop)/elemHeight)*100;
var html="Intro;Read=";
if(prog>100){ prog=100; html="Intro;Read=" }
if(prog<0){ prog=0; }
$("#prog").animate({
"width":""+prog+"%"
},1).html(html+""+prog+"%");
});
});
CSS is irrelevant so not posting it.
Now what I want is:
Is there any way to make this code work for more than one element (say 10 minimum)?
Can anyone design a plugin that will work like say $(elem).scrollProgress() and how? I'm really eager to design one but don't know how to start :(.
Is there any better way to do it?
Any advice, idea, thoughts are greatly appreciated!
Thanks in advance :).
There are already some plugins doing what you want. Check out toc-scrolling-progress.
But if you want it on the whole page you could do something like this:
$(window).scroll(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var distanceToTop = $(window).scrollTop();
var percentScrolled = distanceToTop/(documentHeight - windowHeight) * 100;
$('#progress-bar').css({'width': percentScrolled + '%'});
});
I created a jsfiddle with a demo

Check if two fields has the same value with javascript

I want to make a form for registration and the form should have two fields for password, so there is no mix up.
So if the passwords are the same, there should be a green bock right to the field, and if not there should be a red cross..
So here is my code for testing, but it doesn't work.
<script language="javascript" type="text/javascript">
function check()
{
var loc;
if (test.name1.value == test.name2.value) {
loc = "/img/greenbock.jpg";
}
if (test.name1.value != test.name2.value) {
loc = "/img/redcross.jpg";
}
return loc;
}
</script>
</head>
<body>
<form name="test" method="post" action="">
Name<br />
<input name="name1" type="text" /><br />
Name agian<br />
<input name="name2" type="text" onblur="check()" />
<script language="javascript" type="text/javascript">
if(loc != "")
{
document.write("<div style=\"height:19px; width:20px; background-image:url("+ loc + ")\"></div>");
}
</script>
<br />
Username<br />
<input name="username" type="text" /><br />
So where am I wrong? A little fault or, should i thruw everything away?
[edit]
Now I have set the check-function to run the script after input. So now its doing samething, because everything disapears.. Solutions?
My suggestion would be to let the style of the error/success images be controlled with CSS. Then your validation function can decide what CSS class to assign to a <div> sitting next to your input fields.
Additionally, you will need to add the check() to the other name input in case the user returns to either field later and makes a change.
CSS
/* Shared styling */
.validation-image {
height:19px;
width:20px;
display: none;
}
/* Error styling */
.validation-error {
background-color: #ff0000;
background-image: url('/img/redcross.jpg');
}
/* Success styling */
.validation-success {
background-color: #00ff00;
background-image: url('/img/greenbock.jpg');
}
HTML
<form name="test" method="post" action="">Name
<br />
<input name="name1" type="text" onblur="checkNames()" />
<br />Name agian
<br />
<input name="name2" type="text" onblur="checkNames()" />
<div id="nameValidation" class="validation-image"></div>
<br />Username
<br />
<input name="username" type="text" />
<br />
</form>
JavaScript
function checkNames() {
// Find the validation image div
var validationElement = document.getElementById('nameValidation');
// Get the form values
var name1 = document.forms["test"]["name1"].value;
var name2 = document.forms["test"]["name2"].value;
// Reset the validation element styles
validationElement.style.display = 'none';
validationElement.className = 'validation-image';
// Check if name2 isn't null or undefined or empty
if (name2) {
// Show the validation element
validationElement.style.display = 'inline-block';
// Choose which class to add to the element
validationElement.className +=
(name1 == name2 ? ' validation-success' : ' validation-error');
}
}
Of course, this is a lot more code than you had before, but you could turn this into a re-usable function pretty easily.
jsFiddle Demo
Try this, document.test.name1.value or document.forms["test"]["name1"].value instead of test.name1.value
should be
var loc;
var name1=document.forms["test"]["name1"].value;
var name2=document.forms["test"]["name2"].value;
if(name1== name2){
loc = "/img/greenbock.jpg";
}else {
loc = "/img/redcross.jpg";
}

Google Chrome disable yellow input form field (NO FLASH)

So, I searched for a while to see if I can disable the yellow color bg chrome adds to fields it remembers... This is a little annoying to my theme.
I found this code that fixes it!
<script type="text/javascript">
$(function() {
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
var intervalId = 0;
$(window).load(function() {
intervalId = setInterval(function () { // << somehow this does the trick!
if ($('input:-webkit-autofill').length > 0) {
clearInterval(intervalId);
$('input:-webkit-autofill').each(function () {
var text = $(this).val();
var name = $(this).attr('name');
$(this).after(this.outerHTML).remove();
$('input[name=' + name + ']').val(text);
});
}
}, 1);
});
}
});
</script>
The issue is this little flash of yellow when you try it
Also here is my form....
<form action="login.php" method="post" class="form-container">
<input class="menu_button" type="submit" value="Login">
Register<br>
<input autocomplete="off" class="form-field" value="Username" type="text" name="username" onfocus="if (this.value=='Username') this.value='';"/><br />
<input class="form-field" value="Password" type="password" name="password" onfocus="if (this.value=='Password') this.value='';"/><br />
</form>
Is this simply because Chrome has glitches with it or something of that sort....
Is it even possible to fix?
You could hide the elements with CSS
/* may as well target Chrome (catches Safari too tho) */
#media screen and (-webkit-min-device-pixel-ratio:0){
input{
opacity:0;
}
}
Then show them after that webkit business kicks in.
$('input').css({opacity:1});
Yes they'll be invisible on load but that shouldn't really be noticeable.

Check all input fields have been filled out with jQuery

I have 3 divs, each with a dfew input fields and next button on.
I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.
I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...
http://jsfiddle.net/xG2KS/1/
You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:
$(".next").click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
//At least one input is empty
}
});
Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.
Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.
Here's an updated fiddle.
$('.next').click(function() {
var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
if (emptyInputs.length) {
alert('Fail!');
}
});
Because there is no jQuery selector for this case you can extend jQuery’s selector capabilities.
Assuming you select all :text elements, the extension is:
$.extend($.expr[':'],{
isEmpty: function(e) {
return e.value === '';
}
});
Hence, you can select all empty text fields:
$(this).closest('div').find(':text:isEmpty');
$.extend($.expr[':'], {
isEmpty: function (e) {
return e.value === '';
}
});
$('.next').click(function () {
var missingRequired = $(this).closest('div').find(':text:isEmpty');
console.log('Empty text fields: ' + missingRequired.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
$('.next').click(function() {
var inputs = $(this).parent().find('input[value=""]');
if (!inputs.length) {
// you have empty fields if this section is reached
}
});

Add textbox when button is pressed

I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:
<input name="userfile[]" type="file" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
Is added to a designated area? Keeping in mind adding a number onto the name if the button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question
If possible, I recommend adding jQuery to your project. It makes DOM manipulation easy.
http://api.jquery.com/category/manipulation/
An example might look like this
Add Item
<div id="#wrapper">
<input type="text" value="Description goes here." name="imagedescription1" maxlength="20" onfocus="this.value = '';" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</div>
<script>
$(function(){
var i = 3; // i would be incremented with each add.
$("#myButton").click(function(){
$('<input type="text" value="Description goes here." name="imagedescription' + i + '" maxlength="20" onfocus="this.value = '';" /><br />').appendTo('#wrapper');
});
return false;
});
</script>
You can write a JS function for adding textboxes and call the function when the button is pressed.
The function should go along these lines....
var count;
function functionName()
{
count++;
document.Write('<input type="text" value="..." name="imagedescriptor'+count+'" max..');
}
Hopefully it works.
Try this:
var i = 2;
var sourceTextNode = document.getElementsByName("imagedescription2")[0];
function createTextBox(){
var newNode = sourceTextNode.cloneNode(false);
newNode.setAttribute("name", ++i);
var parent = sourceTextNode.parentNode;
if(parent.lastchild == sourceTextNode) {
parent.appendChild(newNode);
} else {
parent.insertBefore(newNode, sourceTextNode.nextSibling);
}
}
function btnClicked(){
createTextBox();
}
another jQuery solution:
Live Demo
$("#f_add").click(function(e) {
var field = document.createElement('input');
$(field).attr('type', 'text');
$(field).attr('name', 'field[]');
$("#thenewhotness").append(field);
e.preventDefault();
});
<form id="thenewhotness">
<button id="f_add">Add Extra Field</button>
<input type="text" name="field[]">
</form>

Categories