jQueryUI animate(color) doesn't work - javascript

I want to animate background color of input element, but it doesn't works :(
JavaScript (when submit):
function sendImage() {
formularz = $('form#sendImage');
autor = formularz.children('input[name=autor]');
if (autor.val().length < 1 || autor.val().length > 20) {
console.log('start');
autor.animate({
backgroundColor: 'red',
width: '100px',
}, 3000, function() {
console.log('end');
});
}
}
jQuery liblaries:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="jquery-ui/jquery-ui.min.css">
<script src="jquery-ui/external/jquery/jquery.js"></script>
<script src="jquery-ui/jquery-ui.min.js"></script>
<!-- I tried also this -->
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
In JS function works well - logs in console are shown, width of element too is changing, but background color not and it do not show any errors in console.
Any suggestions?

jQuery cannot animate background colours by default. You have two options, first you could use a third party plugin. Secondly, you can use CSS. The latter is preferable. Here's how to do it by setting the transition CSS rule on the element and then just adding the class in your jQuery code.
input {
transition: all 3s;
}
input.error {
background-color: red;
}
function sendImage() {
var $formularz = $('form#sendImage');
var $autor = $formularz.children('input[name=autor]');
if ($autor.val().length < 1 || $autor.val().length > 20) {
$autor.addClass('error');
}
}
Working example

I am pretty sure in Javascript you need to indicate you are adding style to an element via its id. So if you set an element's Id to be autor it would work using the following in your if statement:
document.getElementById('autor').style.background-color="red";

Rory McCrossan, I tested your recommendations and 'backgroundColor' worked well, but later i wanted to check again the backgoundColor and it also works...
So I don't know what was wrong. Mayby some typo or I forgot about somethink.
Sorry for the confusion.

Related

Vanilla javascript, not CSS or jQuery, fade in, fade out image change

I know this is fairly easy in jQuery, but I want to do this in plain 'ol "will be around forever" javascript.
I have a dropdown select on my page. I choose one of 8 options. There is a default image showing on the page. When I select an option, the image changes to that pic. It all works fine.
But I want to make the image change a fade out, fade in switch over because I, like most of you, can't leave well alone. We have to keep fiddling.
The javascript that I have, which is triggered by an onchange="setPicture()" on the select dropdown is:
function setPicture(){
var img = document.getElementById("mySelectTag");
var value = img.options[img.selectedIndex].value;
document.getElementById("myImageDiv").src = value;
}
This works fine. The value of the selected index is a string with the path for each image. I just want a fade out then fade in stuck in there somewhere. I have fiddled about a bit, calling another function before changing the src but no luck.
Can someone point me in the right direction?
The easier way would be to use css keyframes alone.
But from javascript there is the web animation api made for that.
Here is a quick modif from the example, to match your case.
function setPicture(){
alice.animate(
[
{ opacity: 1 },
{ opacity: .1},
{ opacity: 1 }
], {
duration: 3000,
iterations: Infinity
}
)
}
<button onclick="setPicture()">
OPACITY ANIMATION
</button>
<img id="alice"
src="https://mdn.mozillademos.org/files/13843/tumbling-alice_optimized.gif"
>
</img>
How about setting the image default CSS with the opacity of 0 and with transition time
then in JavaScript just add a class that will make the opacity set to 1
HTML:
<img class="img1" src="sampleimg.jpg">
CSS:
.img1 {
opacity: 0;
transition: all .3s;
}
.img1.show {
opacity: 1;
}
JS:
function setPicture() {
var img = document.querySelector('.img1');
img.src = 'urlofnewimage';
img.classList.add('show');
}
Hope this helps.
Juste one function for all :
function fadeOutEffect(target) {
var fadeTarget = document.getElementById(target);
fadeTarget.style.opacity = 1;
fadeTarget.style.transition = "opacity 2s";
fadeTarget.style.opacity = 0;
setTimeout(function(){
fadeTarget.style.display = "none";
}, 2000);;
}

jquery sticky-nav-bar behaving like a css3 animation, how to stop it?

live website is on this address: www.calimousineservice.com
Hi i am making this simple website and the i tried to include a sticky nav on top. everything works as expected so far the only problem is that when i scroll the Jquery acts like a slide-in-animation rather than just sticking to the top of the window right away. also since i attached this my image slider has some kind of lagging when sliding the images. i have all my script and file.js(s) attached at the bottom of the html and here are my javascript for sticky nav in addition to its uploaded js files:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/jquery.cycle2.min.js"></script>
<script>
function makeSticky() {
var myWindow = $(window),
myHeader = $(".navigation");
myWindow.scroll(function() {
if (myWindow.scrollTop() == 0 ) {
myHeader.removeClass("sticky-nav");
} else {
myHeader.addClass("sticky-nav");
}
});
}
$( function() {
makeSticky();
});
</script>
there is another script that will pop up a image on the right of the nav bar when scrolled down:
<script>
function hideImg() {
var myWindow = $(window),
container= $(".nhide");
myWindow.scroll(function() {
if (myWindow.scrollTop() == 0 ) {
container.addClass("nhide");
} else{
container.removeClass("nhide");
}
});
}
$( function() {
hideImg();
});
</script>
please scroll down and up few times to get the glimpse of what i am talking about here. the nav bar, when scrolled, acts like a slide-in-animation(like a css3 animation) i want to remove that. and also the problem with my slider. thank you in advance please let me know if i need to provide more of the codes.
It's fell under the slideshow. To fix it, give your navbar z-index property with value more than the slideshow's z-index.
I guess that z-index:999 can fix it!
UPDATE:
Set your navbar's transition property to 0. Because there seem that there are global selector that is used to set the transition.
Make sure that you are using the most specific selector to prevent other element's rules ruling your navbar.
Example:
#yournavbar_container .navbar {
transition: 0s;
}
Or set all values to default:
#yournavbar_container .navbar {
transition: all 0s ease 0s;
}
You can also use this:
#yournavbar_container .navbar {
transition:none;
transition-delay:0s;
transition-duration:0s;
transition-property:none;
transition-timing-function:ease;
}

Remove css class with animation

I'm creating a table and i want to highlight a specific row.
I did this using:
$this.css('background-color', 'green');
$this.delay(3000).animate({ backgroundColor: $color }, 3000);
$this = the row in question.
$color = the previous row color.
But i want it to work with the a css class, so something like this
$this.addClass('highlight');
The class .highlight will only have a background-color.
The problems is that, after i add the class, i can't the background-color.
If i use:
$this.delay(3000).animate({ backgroundColor: $color }, 3000);
it doesn't seem to work because it doesn't overrides the background-color property of the class .highlight itself.
And i don't see a way to animate a removeClass method or even a switchClass from .highlight to ''.
Is there any solution i'm not thinking off to do this.
Thanks in advance.
Use CSS transitions instead. Better performance and simpler.
Fiddle example
transition:background-color 0.3s linear;
though this doesn't provide as much browser support for the animation, obviously.
You could use jQuery UI's .switchClass which animates all the style changes: .switchClass
Once completed highlighting, use the callback to switch it back.
$('div').click(function() {
$(this).switchClass( "normal", "color", 1000, "easeInOutQuad", function(){
$(this).delay(3000).switchClass( "color", "normal", 1000, "easeInOutQuad" );
});
});
Fiddle me here!
the .animate() function works with "numeric" properties like: height, width, left, etc.. but not with background-color.
You can try this:
$(document).ready( function() {
$('tr.normal').on('click', function() {
$(this)
.hide()
.delay(3000)
.fadeIn('slow')
.toggleClass('highlight');
});
});
You could use jQuery's addClass and removeClass, consider:
if($(document).scrollTop() > 250)
{
$('#div').addClass("show");
}
else
{
$('#div').removeClass("show");
}
});
What this is doing is replacing the original class, such as "hide" with the div class "show", this particular snippet of code displays a banner when the user scrolls 250px down the page.
Remember if you're using this code that it's still better (and smoother) to use CSS3 transitions UNLESS you're considering users who's browsers don't support this, such as IE8-.
EDIT: I just realized the reason you're doing it this way is because you're considering IE7 users. Perfect. I have literally just solved this issue myself.
The workaround I used was to have a css3 transition set up, and a detector with an if statement to use jQuery where transition isn't supported, see below:
var Detect = (function() {
var
//Add CSS properties to test for
props = "transition".split(","),
//Browser prefixes
CSSprefix = "Webkit,Moz,O,ms,Khtml".split(","),
d = document.createElement("detect"),
test = [],
p, pty;
// test prefixed code
function TestPrefixes(prop) {
var
Uprop = prop.charAt(0).toUpperCase() + prop.substr(1),
All = (prop + ' ' + CSSprefix.join(Uprop + ' ') + Uprop).split(' ');
for (var n = 0, np = All.length; n < np; n++) {
if (d.style[All[n]] === "") return true;
}
return false;
}
for (p in props) {
pty = props[p];
test[pty] = TestPrefixes(pty);
}
return test;
}());
if (Detect.transition) {
$(function(){
$(window).scroll(function() {
//your code here
//remember to use an if else

jQuery: equivalent of .live() for CSS?

How do I add CSS to elements that have been dynamically created?
Here is a simple example of what I would like to do:
$(document).ready(function() {
$('#container').html('<p id="hello">hello world</p>');
// The following line doesn't work.
$('#hello').css("background-color", "#FFF");
});
The reason I want to do this, and I can't think of another way of doing it, is that I want to use background colour on alternate rows of a table that is dynamically generated:
$("#results-table tr:even").css("background-color", "#FFF");
I need to use this line of jQuery specifically for IE8 and below, which don't support nth-child CSS selectors.
Actually, your code does work. You might want to check if you don't have multiple elements by that ID.
Edit:
Here's your code, without duplicate IDs: http://jsfiddle.net/FhTU7/
Final edit:
Your HTML background and element background are both white.
You could instead of directly setting the CSS also just add a class to the even rows
$("#results-table tr:even").addClass("alt");
CSS to set the row colours and then a different set of colours for the alternate rows
<style type="text/css">
tr
{
background: #fff;
color: #000;
}
tr.alt
{
background: #000;
color: #fff;
}
</style>
You could declare the new element as a variable...
$(document).ready(function() {
var $new = $('<p id="hello">hello world</p>');
$new.css({
backgroundColor: "#fff"
})
$('#container').append($new);
});
You could use appendTo...
$(document).ready(function() {
$('<p id="hello">hello world</p>').appendTo('#container').css({
backgroundColor: "#fff"
})
});
However, if you create the elements correctly then you can use the original CSS at the end...
$('#container').append('<p id="hello">hello world</p>');

Wait cursor over entire html page

Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:
if an element (#id1) has a cursor style set it will ignore the one set on body (obviously)
some elements have a default cursor style (a) and will not show the wait cursor on hover
the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer
The test:
<html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
Do something
</body>
</html>
Later edit...
It worked in firefox and IE with:
div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)
Later later edit...
A simpler solution from Dorward:
.wait, .wait * { cursor: wait !important; }
and then
Do something
This solution only shows the wait cursor but allows clicks.
If you use this slightly modified version of the CSS you posted from Dorward,
html.wait, html.wait * { cursor: wait !important; }
you can then add some really simple jQuery to work for all ajax calls:
$(document).ready(function () {
$(document).ajaxStart(function () { $("html").addClass("wait"); });
$(document).ajaxStop(function () { $("html").removeClass("wait"); });
});
or, for older jQuery versions (before 1.9):
$(document).ready(function () {
$("html").ajaxStart(function () { $(this).addClass("wait"); });
$("html").ajaxStop(function () { $(this).removeClass("wait"); });
});
I understand you may not have control over this, but you might instead go for a "masking" div that covers the entire body with a z-index higher than 1. The center part of the div could contain a loading message if you like.
Then, you can set the cursor to wait on the div and don't have to worry about links as they are "under" your masking div. Here's some example CSS for the "masking div":
body { height: 100%; }
div#mask { cursor: wait; z-index: 999; height: 100%; width: 100%; }
This seems to work in firefox
<style>
*{ cursor: inherit;}
body{ cursor: wait;}
</style>
The * part ensures that the cursor doesn't change when you hover over a link. Although links will still be clickable.
I have been struggling with this problem for hours today.
Basically everything was working just fine in FireFox but (of course) not in IE.
In IE the wait cursor was showing AFTER the time consuming function was executed.
I finally found the trick on this site:
http://www.codingforums.com/archive/index.php/t-37185.html
Code:
//...
document.body.style.cursor = 'wait';
setTimeout(this.SomeLongFunction, 1);
//setTimeout syntax when calling a function with parameters
//setTimeout(function() {MyClass.SomeLongFunction(someParam);}, 1);
//no () after function name this is a function ref not a function call
setTimeout(this.SetDefaultCursor, 1);
...
function SetDefaultCursor() {document.body.style.cursor = 'default';}
function SomeLongFunction(someParam) {...}
My code runs in a JavaScript class hence the this and MyClass (MyClass is a singleton).
I had the same problems when trying to display a div as described on this page. In IE it was showing after the function had been executed. So I guess this trick would solve that problem too.
Thanks a zillion time to glenngv the author of the post. You really made my day!!!
Easiest way I know is using JQuery like this:
$('*').css('cursor','wait');
css: .waiting * { cursor: 'wait' }
jQuery: $('body').toggleClass('waiting');
Why don't you just use one of those fancy loading graphics (eg: http://ajaxload.info/)? The waiting cursor is for the browser itself - so whenever it appears it has something to do with the browser and not with the page.
To set the cursor from JavaScript for the whole window, use:
document.documentElement.style.cursor = 'wait';
From CSS:
html { cursor: wait; }
Add further logic as needed.
Try the css:
html.waiting {
cursor: wait;
}
It seems that if the property body is used as apposed to html it doesn't show the wait cursor over the whole page. Furthermore if you use a css class you can easily control when it actually shows it.
Here is a more elaborate solution that does not require external CSS:
function changeCursor(elem, cursor, decendents) {
if (!elem) elem=$('body');
// remove all classes starting with changeCursor-
elem.removeClass (function (index, css) {
return (css.match (/(^|\s)changeCursor-\S+/g) || []).join(' ');
});
if (!cursor) return;
if (typeof decendents==='undefined' || decendents===null) decendents=true;
let cname;
if (decendents) {
cname='changeCursor-Dec-'+cursor;
if ($('style:contains("'+cname+'")').length < 1) $('<style>').text('.'+cname+' , .'+cname+' * { cursor: '+cursor+' !important; }').appendTo('head');
} else {
cname='changeCursor-'+cursor;
if ($('style:contains("'+cname+'")').length < 1) $('<style>').text('.'+cname+' { cursor: '+cursor+' !important; }').appendTo('head');
}
elem.addClass(cname);
}
with this you can do:
changeCursor(, 'wait'); // wait cursor on all decendents of body
changeCursor($('#id'), 'wait', false); // wait cursor on elem with id only
changeCursor(); // remove changed cursor from body
I used a adaptation of Eric Wendelin's solution. It will show a transparent, animated overlay wait-div over the whole body, the click will be blocked by the wait-div while visible:
css:
div#waitMask {
z-index: 999;
position: absolute;
top: 0;
right: 0;
height: 100%;
width: 100%;
cursor: wait;
background-color: #000;
opacity: 0;
transition-duration: 0.5s;
-webkit-transition-duration: 0.5s;
}
js:
// to show it
$("#waitMask").show();
$("#waitMask").css("opacity"); // must read it first
$("#waitMask").css("opacity", "0.8");
...
// to hide it
$("#waitMask").css("opacity", "0");
setTimeout(function() {
$("#waitMask").hide();
}, 500) // wait for animation to end
html:
<body>
<div id="waitMask" style="display:none;"> </div>
... rest of html ...
My Two pence:
Step 1:
Declare an array. This will be used to store the original cursors that were assigned:
var vArrOriginalCursors = new Array(2);
Step 2:
Implement the function cursorModifyEntirePage
function CursorModifyEntirePage(CursorType){
var elements = document.body.getElementsByTagName('*');
alert("These are the elements found:" + elements.length);
let lclCntr = 0;
vArrOriginalCursors.length = elements.length;
for(lclCntr = 0; lclCntr < elements.length; lclCntr++){
vArrOriginalCursors[lclCntr] = elements[lclCntr].style.cursor;
elements[lclCntr].style.cursor = CursorType;
}
}
What it does:
Gets all the elements on the page. Stores the original cursors assigned to them in the array declared in step 1. Modifies the cursors to the desired cursor as passed by parameter CursorType
Step 3:
Restore the cursors on the page
function CursorRestoreEntirePage(){
let lclCntr = 0;
var elements = document.body.getElementsByTagName('*');
for(lclCntr = 0; lclCntr < elements.length; lclCntr++){
elements[lclCntr].style.cursor = vArrOriginalCursors[lclCntr];
}
}
I have run this in an application and it works fine.
Only caveat is that I have not tested it when you are dynamically adding the elements.
BlockUI is the answer for everything. Give it a try.
http://www.malsup.com/jquery/block/
This pure JavaScript seems to work pretty well ... tested on FireFox, Chrome, and Edge browsers.
I'm not sure about the performance of this if you had an overabundance of elements on your page and a slow computer ... try it and see.
Set cursor for all elements to wait:
Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = "wait");
Set cursor for all elements back to default:
Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = "default");
An alternative (and perhaps a bit more readable) version would be to create a setCursor function as follows:
function setCursor(cursor)
{
var x = document.querySelectorAll("*");
for (var i = 0; i < x.length; i++)
{
x[i].style.cursor = cursor;
}
}
and then call
setCursor("wait");
and
setCursor("default");
to set the wait cursor and default cursor respectively.
Lots of good answers already, but none of them mentions the <dialog> element.
Using this element we can create a solution similar to the masking <div>.
Here we use showModal() to "hide" elements, and we use ::backdrop to set the cursor style to wait on the entire page:
function showWaitDialog() {
document.getElementById('id_dialog').showModal();
}
#id_dialog, #id_dialog::backdrop {
cursor: wait;
}
<button onclick="showWaitDialog()">click me</button>
<dialog id="id_dialog">busy...</dialog>
The dialog is hidden by default, and can be shown using either the show() method, or the showModal() method, which prevents clicking outside the dialog.
The dialog can be forced to close using the close() method, if necessary.
However, if your button links to another page, for example, then the dialog will disappear automatically as soon as the new page is loaded.
Note that the dialog can also be closed at any time by hitting the Esc key.
CSS can be used to style the dialog however you like.
The example uses the html onclick attribute, just for simplicity. Obviously, addEventListener() could also be used.
Late to the party but simply give the Html tag an id by targeting
document.documentElement
and in the CSS place at the top
html#wait * {
cursor: wait !important;
}
and simply remove it when you want to stop this cursor.

Categories

Resources