<div class="example">
Test
</div>
$('.example').click(function(){
$(this).css('color','red');
});
When the code above get's clicked, it will apply the .css. Now what I need is for another bit of code (let's say $(this).css('color','blue');) to be applied, replacing the previous code when .example gets clicked a second time.
I've searched for this and askers seem to only need .show/.hide events which can be substituted with .toggle, which is obviously not the case here.
Since you may have many instances of class example, simply maintaining a state using a single variable is not feasible, what you can do is to maintain the state of each instance of example within itself:
Define two css classes
.example { background:blue }
.example.red { background:red }
Then your click method:
$('.example').click(function(){
$(this).toggleClass('red');
});
If you prefer not to define new css classes, you can use data(), to make sure that the state is exclusive within each .example, this is useful if you have many instances of .example
$('.example').click(function() {
var color = $(this).data('color');
if(color != 'blue') {
$(this).css('color', 'blue');
$(this).data('color', 'blue');
} else {
$(this).css('color', 'red');
$(this).data('color', 'red');
}
});
http://api.jquery.com/data/
Something like this would work to toggle between 2 colours (or styles).
$('.example').click(function(){
if($(this).css('color') == "red")
{
$(this).css('color','blue');
}
else
{
$(this).css('color','red');
}
});
<div class="example">
Test
</div>
just maintain a bool and you are done..
var isRed=false;
$('.example').click(function(){
if(isRed)
{
$(this).css('color','blue');
isRed=false;
}
else
{
$(this).css('color','red');
isRed=true;
}
});
Use addClass and removeClass
.blueColor
{
background-color: blue;
}
.redColor
{
background-color: red;
}
And use in your javascript the addClass and removeClass functions:
<script>
$(document).ready(function(){
$(".example").keypress(function() {
if($(".example").val().length > 0)
{
$(".example").addClass("redColor");
}
else {
if($(".example").val().length == 0)
{
$(".example").addClass("blueColor");
$(".example").removeClass("redColor");
}
}
});
});
</script>
I guess you need something more generic about click event exactly so I'd suggest you to use data method to leave the flags
$('.example').click(function() {
if (!$(this).data("custom-even")) {
// odd execution
$(this).data("custom-even", true)
} else {
// even execution
$(this).data("custom-even", false)
}
});
$('.example').click(function(){
var theExample = $(this);
if(theExample.hasClass("clicked")){
theExample.css('color','blue').removeClass("clicked");
}else{
theExample.css('color','red').addClass("clicked");
}
});
http://jsfiddle.net/SnDgh/
Hiya Try this with toggle :)) http://jsfiddle.net/FVXAZ/
SO you can use toggle with your css and every second click will have the vice-a-versa affect. :)
Code
$(function() {
$('.example').toggle(function() {
$(this).css('color','red');
}, function() {
$(this).css('color','blue');
});
});
Have a nice man man, cheers!
Try this:
$('.example').click(function(){
if($('.example').data('isAlreadyClicked')=='true')
{
$(this).css('color','blue');
$('.example').data('isAlreadyClicked','false')
}
else
{
$(this).css('color','red');
$('.example').data('isAlreadyClicked','true')
}
});
Use the one method to handle one-time event binding is a good choice, however this solution will stop all events binded after this code, it may cause inconsistency.
$('.example')
.one('click', function(e) {
e.stopImmediagePropagation();
})
.on('click', function() {
$(this).css('color', blue');
});
Lot of answers all defining a single solution.
Basically, there are two ways that you should use. The other ways mentionned are either unperformant or unsemantic (using data for this kind of solution is overkill). Here are the two ways you may use:
// Toggle a class 'red' defined in your stylesheet
$('.example').on('click', function() {
$(this).toggleClass('red')
})
// Toggle the color with an "if" check
$('.example').on('click', function() {
if (this.style.color === 'red') { // using jQuery is not required
this.style.color === 'blue'
}
else {
this.style.color === 'red'
}
})
You can write:
$('#id').toggle(function() {
$('.css').css('color','red');}
,function() { /////////the second click
$('.css').css('color','blue');}
);
Related
Trying to get this javascript to read the value of the div "flow-hold" and change the background color based on the value.
I have a div named flow hold with a value of 132 for example, that I would like to see green because it is less than the 200 threshold. If the value exceeds the threshold, I would like it to be red.
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold'), function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
try this simple and easy:
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 200) {
$(this).css("background-color","red");
} else {
$(this).css("background-color","green");
}
});
If you want to do it on page load you could use your Back-End technology to assign a CSS class with demanded color according to the threshold.
For example, in PHP it would be:
<div class="flow-hold <?=($threshold>=200)?'bg-red':'bg-green'?>">132</div>
In your CSS file:
bg-red{
background-color: red;
}
bg-green:{
background-color: green;
}
However, if you want to do it on client-side, you have to allocate an exact action to it, for instance:
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold').on('hover', function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
actually your problem are the accessors that you are using. check that if you use JQuery and get the items by class you will get an array with all the divs containing that class.
so here you have a working example of what you wanted to achieve taking into account what I told before.
NOTE: your code doesn't run by itself, next time please fix it.
NOTE2: note that I didn't do a lot of changes and it started to work.
function changeBackground() {
let div = $('.flow-hold')[0];
if (div.innerText >= 200) {
$('.flow-hold').css({
"background-color": "red"
});
} else {
$('.flow-hold').css({
"background-color": "green"
});
}
}
changeBackground();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flow-hold">132</div>
You can use the script below:
$(document).ready(function(){
var value = parseInt($('.flow-hold').html());
if(value >= 200){
$('.flow-hold').css("background-color","red");
}
else {
$('.flow-hold').css("background-color","green");
}
});
I believe you intended to use the .each( function ) jQuery method, where the function should only handle one element at a time, so it shouldn't lookup $('.flow-hold') again, since there can be more than one element with that class.
You should also use the .text() method, not the .val() method.
$('.flow-hold').each(function() {
if ($(this).text() >= 200) {
$(this).css({"background-color":"red"});
} else {
$(this).css({"background-color":"green"});
}
});
Since you are setting the same property in both cases, you can also use the implicit looping of the .css( propertyName, function ) method:
$('.flow-hold').css("background-color", function() {
return ($(this).text() >= 200 ? "red" : "green");
});
I am trying to understand how javascript (jquery in this case) if statements work. I thought i understood but i don't fully get some things. Please see the code below. Why is it when i click on the element with the class of "cat" that it does not remove the class of "black" and add the class of "red".
$(function() {
var cat = true;
$( ".cat" ).click(function() {
cat = false;
});
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
i know there is probably a very simple answer to this but i'm just learning so any help would be appreciated, thanks in advance.
Toggle the value of cat and put the if block inside the function that you want to bind with the event 'click':
$(".cat").click(function() {
cat = !cat;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
Edit: Simpler way to do this is to use .toggleClass():
$(".cat").click(function() {
$(this).toggleClass('red black');
});
If you want to check on click, put the if inside the click event. The reason why your solution doesn't work is because you attach a listener to the element, but you immediately do a check. The check doesn't happen every time the user clicks, just once. You must put it in the listener's callback function so it executes every time the element is clicked:
$(function() {
$(".cat").click(function() {
$(".cat").toggleClass("black red");
});
});
How this works is it attaches a click event to .cat and, on click, toggles the classes black and red. This completely gets rid of the checking because that isn't necessary. Just toggle the classes on click. Also, no need to repeat the selector, just use this. Here's a snippet:
$(function() {
$(".cat").click(function() {
$(this).toggleClass("black red");
});
});
.black {
color: black;
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat red">Test</div>
Your code is not removing class black and adding class red because your if(){}else{} code block running when your page is loading. When you are clicking the cat class it is only assigning the value of cat variable to false. since your if else code block is out of your click function that is why it is not executing again. and that is why it is not working. To work your code place your if else code block in the click function like this:
$( ".cat" ).click(function() {
cat = false;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
};
});
How do I toggle the text of an element with jQuery .click(), .toggle() and .text() only?
You can use a variable to hold the text to be toggled.
But please no classes to be turned off and on with .toggle().
One way you could do this is to change the class of an element to change your css differennces. If you want to add text or additional elements. Look into the .append() function in jQuery.
However, just a personal opinion here, AngularJS would make that kind of stuff very easy to do. If you haven't learned any frameworks yet, I suggest you take a look at it.
Try something like this,
var toggleText = "toggle",
value;
$('div').click(function() {
$(this).text(function(i, v) {
if (v == toggleText)
return value;
else {
value = v;
return toggleText;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>hi.....</div>
You could use .data()
$(this).data('toggle', 0); // initial data
$('div').click(function() { // on click
if($(this).data('toggle') === 0) { // if toggle is off
$(this).data('toggle', 1); // turn toggle on
} else { // if toggle on
$(this).data('toggle', 0); // turn toggle off
}
$(this).append($(this).data('toggle'));
});
Here's a JSFiddle
im trying to check if one of the DIV's has class "visible" which is being add by a jquery plugin, it seems not to work.
it works when i check the first element, but if i want to check next div, it doenst finds it.
help is appreciated.
My DIV
<div class="swiper-slide welcome" id="welcome"></div>
2nd DIV
<div class="swiper-slide intro-early-life" id="intro-early-life"></div>
MY JQUERY
<script type="text/javascript">
$(document).ready(function() {
if ($('.welcome').hasClass('swiper-slide-visible')) {
alert("working");
}
});
</script>
Im not using same ID, maybe it was my bad explanation. I can use the class as well, no difference.
$(document).ready(function() {
if ($('#welcome').hasClass('swiper-slide') && $('#welcome').hasClass('visible')) {
alert("working");
}
});
if ($('#welcome').is(":visible") && $('#welcome').hasClass("swiper-slide")) {
alert("Yeah!");
}
Perhaps that would work better?
Edit: Also swiper-slide-visible class doesn't exist on the page - perhaps this is the issue...?
You can use also as
$(document).ready(function() {
if ($('#welcome').hasClasses(['swiper-slide', 'visible']);) {
alert("working");
}
});
$.fn.extend({
hasClasses: function (selectors) {
var self = this;
for (var i in selectors) {
if ($(self).hasClass(selectors[i]))
return true;
}
return false;
}
});
Use .is()
if ($('#welcome').is('.swiper-slide, .visible'){
Id Must Be unique you can use classes instaed
Two HTML elements with same id attribute: How bad is it really?
You could use .is() instead:
$(document).ready(function() {
if ($('.welcome').is('.swiper-slide.visible')) {
alert("working");
}
});
I am trying to write an if else statement to trigger one class when another one is clicked under the condition that the one class has a marginTop of -200px.
I tried using this if statement but it doesn't work:
if ($('.logintrigger').click() && $('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {$('.register').stop().animate({'marginTop':'-0px'},200); $('#opencloseregister').css({'backgroundPosition':'-20px 0px'});}
);
}
Any suggestions???
Made a jsfiddle with an example of proper ifelse with jquery. http://jsfiddle.net/RQ75m/
$(".logintrigger").click(function(){
if( $(".register").css("margin-top") == "200px" ){
$(".registertrigger").show(); //toggle function here
return false; //so that the page doesn't refresh
} else {
$(".registertrigger").hide();
return false; //so that the page doesn't refresh
}
});
It sounds like you simply need to rework your expression. The problem is you're trying to see if an element is 'clicked', when you should just attach an event handler.
$('.loginTrigger').click(function()
{
if('.register').css('marginTop') === '-200px')
{
// Do Stuff
}
});
you are calling the click event, i think you want to add an event to the click event...
$('.logintrigger').click( function(e){
if($('.register').css('marginTop') === '-200px'){
$('.registertrigger').toggle();
}
});
When you are calling $('.logintrigger').click(), it is triggering click event.
it should be:
if ($('.logintrigger').click(function(){
if ($('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {
$('.register').stop().animate({'marginTop':'-0px'},200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
}
);
}
})
$('.logintrigger').on('click', function(){
if($('.register').css('marginTop')==='200px') {
$('.registertrigger').toggle( function () {
$('.register').stop().animate({'marginTop': 0 },200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
});
}
});