jQuery mouseenter functions - changing colour if colour isn't already - javascript

So, I am not that fluent with jQuery and I have written a bit of code in it that doesn't look as if it works. Here is my code;
$(document).ready(function() {
$("#loginSelector").mouseenter(function() {
if $("#loginSelector").style.backgroundColor != "#3064CA" {
$("#loginSelector").style.backgroundColor = "#3064CA";
};
});
$("#loginSelector").mouseleave(function() {
if $("#loginSelector").style.backgroundColor != "#5990DE" {
$("#loginSelector").style.backgroundColor = "#5990DE";
};
});
$("#signupSelector").mouseenter(function() {
if $("#signupSelector").style.backgroundColor != "#3064CA" {
$("#signupSelector").style.backgroundColor = "#3064CA";
};
});
$("#signupSelector").mouseleave(function() {
if $("#signupSelector").style.backgroundColor != "#5990DE" {
$("#signupSelector").style.backgroundColor = "#5990DE";
};
});
});
All I want the code to do is check to see if the button is not a certain colour, and if it isn't that colour and it is hovered on, it changes to another colour.

Try this and follow the same for the rest of the blocks.
$("#loginSelector").mouseenter(function() { //when hovered on
var desiredColor = "#3064CA"; //define the desired color
if ( $(this).css('color') === desiredColor) return; //if the element's color = the desired color, don't do anything. stop the execution
$(this).css('color', desiredColor); //else set the desired color
});

Assuming the elements initially have the color #5990DE, I'd simply add the following css:
#loginSelector, #signupSelector{
background: #5990DE;
}
#loginSelector:hover, #signupSelector:hover{
background: #3064CA;
}
Or if otherwise,
css:
.onHover{
background: #3064CA;
}
.onLeave{
background: #5990DE;
}
script:
$(document).on('mouseenter', 'loginSelector , #signupSelector', function(){
$(this).addClass('onHover').removeClass('onLeave');
});
$(document).on('mouseleave', '#loginSelector , #signupSelector', function(){
$(this).addClass('onLeave').removeClass('onHover');
});

Related

Why can I only change the css style once in javascript?

I want to be able to change the backgroundColor of a box between multiple colors using js but I cannot seem to find a way. Is it possible?
window.onload = function() {
var example=document.getElementById("example");
var click=0;
example.addEventListener("click", func);
function func(){
if (click===0){
example.style.backgroundColor=("red");
click=1;
}
if (click===1){
example.style.backgroundColor=("blue");}
click=0;
}
}
Your code checks to see if the value is zero. When it is, it sets it to one. Right after that if statement you see if it is one and set it back to zero.
You need to use else if or just else so it does not evaluate the next if statement.
function func(){
if (click === 0){
example.style.backgroundColor = "red";
click = 1;
}
//else if (click === 1) {
else {
example.style.backgroundColor = "blue";
click = 0;
}
}
Personally I would just toggle a class
var elem = document.querySelector("#test")
elem.addEventListener("click", function () {
elem.classList.toggle("on");
});
div.example {
background-color: blue;
}
div.example.on {
background-color: lime;
}
<div id="test" class="example">Click Me</div>

jQuery: check if element has specific style (not inline)

Is it possible to check via jQuery or vanilla JS if an element has a specific style?
In my case I want to check if any input-fields on the page have a red border — applied via an external CSS-File. No inline-css and no style-attr is available, styling is completely external.
For my initial testing I got the following code from this StackOverflow-Answer: https://stackoverflow.com/a/29659187
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).css('border-color') === 'rgb(255,0,0)'
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
… but .css seams to only test inlineStyles.
Update
I can't change HTML, the markup has to stay «as is». The red border is coming through css only. Like this: https://jsfiddle.net/z3t6k04s/
Try it like this:
$('.formValidation input[type=submit]').on('click',function(e){
// Prevent Default Form Submit
e.preventDefault();
// Define Global if Invalid Fields Exist
var hasInvalidInputs = false;
// Run Through all to check Input Fields
$('input').filter(function(index){
// Check if Invalid Inputs already got detected. If not - check if this field is red
if( !hasInvalidInputs )
hasInvalidInputs = $(this).css('border-color') == 'rgb(161, 0, 0)'; // If field is red -> update global var to true
});
// Check if Invalid Fields are set to true
if (hasInvalidInputs) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
You could use
Window.getComputedStyle()
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
Example:
var inp = document.getElementsByTagName('input')[0];
var style = window.getComputedStyle(inp, null);
console.log(style.getPropertyValue("border-color"))
input[type='text'] {
border: 1px solid rgb(255, 0, 0);
}
<input type="text" value="Foo" />
Create a one class which has a red color
like
.red-color{
border-color:red;
}
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).hasClass('red-color');
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
I hope this will helpful to you.
You can use below code
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var isValid;
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
element.css('border-color','red');
}else{
isValid = true;
element.css('border-color','');
}
});
if (isValid==false) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});

Form validation within tabs assistance required

Please see a working demo of my form so far: Demo Fiddle
I have it working so that if you do not fill in the fields it will not allow you to move onto the next tabs. However, if you fail to validate and then fill in the details the boxes stay red. I need some assistance with clearing the queried boxes once you fill them in.
jQuery(document).ready(function($) {
var currentTab;
$(".tabs-menu a, .tab-content .next").click(function(event) {
event.preventDefault();
var $this = $(this),
requiredAreFilled = true,
tab = $this.attr("href") || $this.data('next'),
currentTab = $('.tabs-menu .current').children('a').attr('href');
$(currentTab).find('.required').each(function(index, elt) {
if ($(elt).val() === '') {
requiredAreFilled = false;
$(elt).css('border', '2px solid #FB8183'); // This is bad, should be a class
}
});
var tabLink = $this.is('a') ? $this.parent() : $('.' + tab.substring(1)),
$tabLink = $(tabLink);
console.log($tabLink);
if (requiredAreFilled) {
$tabLink.addClass("current")
.siblings().removeClass("current");
$(".tab-content").not(tab).hide();
$(tab).fadeIn();
}
});
});
Your JSFiddle repaired
.required-error { /* new class */
border: 2px solid #FB8183;
}
jQuery(document).ready(function ($) {
var currentTab;
$(".tabs-menu a, .tab-content .next").click(function (event) {
event.preventDefault();
var $this = $(this),
requiredAreFilled = true,
tab = $this.attr("href") || $this.data('next'),
currentTab = $('.tabs-menu .current').children('a').attr('href');
$(currentTab).find('.required').each(function (index, elt) {
if ($(elt).val() === '') {
requiredAreFilled = false;
$(elt).addClass('required-error'); // This is bad, should be a class
} else {
/* this will fix the "corrected" inputs */
$(elt).removeClass('required-error');
}
});
var tabLink = $this.is('a') ? $this.parent() : $('.' + tab.substring(1)),
$tabLink = $(tabLink);
console.log($tabLink);
if (requiredAreFilled) {
$tabLink.addClass("current")
.siblings().removeClass("current");
$(".tab-content").not(tab).hide();
$(tab).fadeIn();
}
});
});
Just trigger the keyUp event on the input fields to remove the border :)
$('input[type="text"]').keyup(function() {
//remove the border
});
Y don't use a validation plugin, if you already use jQuery?
There are a lot of good Plugins out there:
http://formvalidator.net/
If you use Bootstrap i recommend: http://bootstrapvalidator.com/
Try this : DEMO focusout, DEMO keyup
Basically this js is added :
$(".tab-content").on("focusout",".invalidInput",function() {
if($.trim($(this).val()).length>0)
$(this).removeClass("invalidInput");
});
and used a css class :
.invalidInput{
border : 2px solid #FB8183;
}
This removes the border when the textbox focus is taken away, if you need it to happen as soon as user enters data, use keyup instead of focusout

How to add js var inside jquery

Somehow I can't make the var "turn" change.
--------------'#a3' is a div-----------------
For all of the code go here.
Here is some of the js/jquery:
var turn = 1;
if (turn === 1) {
//----------------------------red
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "red");
turn = 0;
});
}
if (turn === 0) {
//----------------------------blue
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "blue");
turn = 1;
});
}
Here is some css I used:
div {
display: inline-block;
background-color:grey;
width : 150px;
height: 150px;
}
It is because you only add one event handler that only does one thing. It is not magically going to add the other one.
Do the if/else logic inside of the click events.
If you want to toggle the background-color by clicking the a3-element, you need to do the if/else checking inside of the event-handler:
bg_state = 0;
$('#a3').click(function () {
if (bg_state===0) {
$(this).css("background-color", "blue");
bg_state=1;
} else {
$(this).css("background-color", "red");
bg_state=0;
}
});
http://jsfiddle.net/ADUV9/
The setting of the event-handler is only executed one time, when the page loads!
Your current code is structured like this:
var turn = 1; // red turn first
if (turn === 1) {
// assign click handlers for red moves
}
if (turn === 0) {
// assign click handlers for blue moves
}
The problem with this is that the only click handlers that will ever be used here are the ones defined in the if (turn === 1) block. The code will not be re-evaluated when you modify turn so the click handlers for blue will never be used.
Instead it should look something like this:
var turn = 1; // red turn first
// example click handler:
$('#a3').click(function () {
// check whose turn it is *inside* of the click handler
if (turn === 0) {
$(this).css("background-color", "blue");
turn = 1;
} else {
$(this).css("background-color", "red");
turn = 0;
}
});
// other click handlers like the above (or better yet, reuse the same function)

jQuery hover on the same element

With jQuery hover how do you check if you've just hovered on the same element again? Say I have two boxes and hover on box 1, then left, then come back and hover on that same box. I'd like to store the value of the initial hovered element (box 1) and then compare if it's the same when hovering back.
Thanks!!
Try something like below,
var lastHovered = '';
$('#box1').hover(function () {
if (lastHovered == 'box1') {
alert('You have hovered on this already');
}
lastHovered = 'box1';
//Your stuff
}, function () {
//mouse out stuff
});
$('#box2').hover(function () {
if (lastHovered == 'box2') {
alert('You have hovered on this already');
}
lastHovered = 'box2';
//Your stuff
}, function () {
//mouse out stuff
});
Note: I have used 2 functions assuming that box1 hover and box2 hover has totally different functionalities... If not you can have it inside same function and use this.id to group them.. see below.
var lastHovered = '';
$('#box1, #box2').hover(function () {
if (lastHovered == this.id) { //<-- used this.id instead of hard-coded value
alert('You have hovered on ' + this.id + ' already');
}
lastHovered = this.id; //<-- used this.id instead of hard-coded value
//Your stuff
}, function () {
//mouse out stuff
});
Use .data() http://api.jquery.com/data/ so on first hover in the callback do something like
if (!$(this).data('var')) {
$(this).data('var','value');
} else {
console.log($(this).data('var'));
};
var lastHovered = null;
$('#selector1,#selector2,#selector3').hover(function (evt) {
if(lastHovered && lastHovered === $(this).attr("id")){
//code for 're-hovering'
}else{
//code for 'new hover'
}
}, function (evt) {
//mouse out stuff
lastHovered = $(this).attr("id");
});

Categories