How to handle class (made by jQuery) with jQuery? - javascript

I'm new in jQuery. This time I tried to make a double-stage effect using jQuery.
For example, when you click the word, its color changed to red at first. And when you clicked it again, its color changed to blue.
So I used following code, but it doesn't work well.
$(document).ready(function () {
$("p#origin").click(function () {
$(this).css("color", "red");
$(this).addClass("clicked");
});
$("p.clicked").click(function () {
$(this).css("color", "blue");
});
});
You can see the result at here
I also tried this.
var toggle = 0;
console.log("toggle", toggle);
$(document).ready(function () {
if (toggle == 0) {
$("p#origin").click(function () {
$(this).css("color", "red");
toggle = 1;
console.log("toggle:", toggle);
});
} else {
$("p#origin").click(function () {
$(this).css("color", "blue");
toggle = 0;
console.log("toggle", toggle);
});
}
});
Above code result can be seen here. The variable toggle is set to 1, but it doesn't work.
Is my question delivered well...? I'm new here, so I don't know how the javascript code loaded. (I also need help to study about this...)
I hope any solution to make a double stage effect. (Could anyone fix my above 2 codes to work well?)

The problem is you are dealing with dynamic selectors, ie you want the events handled to change based on dynamic evaluation of the selector, in that case you need to use event delegation.
But in this case you don't need that, assuming at first the p#origin does not have blue color you can do something like
$(document).ready(function() {
$("p#origin").click(function() {
$(this).toggleClass("clicked").toggleClass('unclicked', !$(this).hasClass('clicked'));
});
});
#origin.unclicked {
color: blue;
}
#origin.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="origin">origin</p>
But if p#origin has blue color before the first click, then you can simplify it to
$(document).ready(function() {
$("p#origin").click(function() {
$(this).toggleClass("clicked");
});
});
#origin {
color: blue;
}
#origin.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="origin">origin</p>

Just an idea instead of using .class:
Loop an array of styles (you can use as many styles/steps you want)
var c = ["#000", "#f00", "blue"];
$("#origin").click(function(){
c.push(c.shift()); // Put first array color to last place
$(this).css({color: c[0] }); // Always use the 0 key
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="origin">Click to Toggle Color</p>
If you want to change more than just a color:
var c = [
{color:"#000", background:"#ffe", fontSize:16},
{color:"fuchsia", background:"yellow", fontSize:24},
{color:"#1CEA6E", background:"#C0FFEE", fontSize:36}
];
$("#origin").click(function(){
c.push(c.shift());
$(this).css(c[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="origin">Click to loop styles</p>

I just modified some JavaScript code from you, simply.
var $origin;
$origin = $('#origin');
return $origin.on('click', function() {
if ($origin.hasClass('red')) {
$origin.css('color', 'yellow');
$origin.addClass('yellow');
return $origin.removeClass('red');
} else {
$origin.css('color', 'red');
$origin.addClass('red');
return $origin.removeClass('yellow');
}
});

Related

CSS toggler using Javascript

I want to toggle the white-space style of a tr element to normal when the tr is clicked. I've managed to take a function used for toggling colours and adapt this for my purposes, however I can only make the class change toggle once, and don't know how to change the this.style.background in line 3 to this.style.white-space, without breaking everything:
$(document).ready(function () {
$('tr').click(function () {
if(this.style.background == "" || this.style.background =="white") {
$(this).css('white-space', 'normal');
}
else {
$(this).css('white-space', 'nowrap');
}
});
});
I know this is fairly basic, however I've only started using JavaScript today, so if anyone could show me the solution and explain what needs to be done then I'd be very appreciative.
You just need to change the if condition so it depends on the value of white-space property:
$(document).ready(function () {
$('tr').click(function () {
var $this = $(this);
if($this.css('white-space') === 'nowrap') {
$this.css('white-space', 'normal');
}
else {
$this.css('white-space', 'nowrap');
}
});
});
You just need to use white-space for your ifstatements, and refactor those if statements. Fixed code below:
$(document).ready(function () {
$('tr').click(function () {
if($(this).css("white-space") == "nowrap") {
$(this).css('white-space', 'normal');
}
else {
$(this).css('white-space', 'nowrap');
}
});
});
Hopefully this helps!

Why won't my jQuery code run?

First off, I apologize for the extremely elementary question. I am a complete newbie and have been teaching myself without any outside help. Be gentle.
I am completing an exercise from a free web dev course, and one of the steps is to add background color to some divs using jQuery. I have used both .hover and .mouseover methods, but neither are working. If I put the code outside of the $(document).ready brackets, nothing happens. If I put the code inside of it, all of my work looks like it's erased.
Here's the code:
$(".pixel").hover(function(){
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "red");
});
Inside the $(document).ready function I created lots of divs with class="pixel", so I figured I should be able to select them using the above code.
Edit:
Again, I am sorry it seems I'm not including enough information. This is literally my first attempt at posting something here. I have nobody I can ask these questions to.
Here is the beginning of my .js file, before the .hover code I'm trying to run:
$(document).ready(function() {
$("body").append("<div id='main'>");
for (var i=0; i<256; i++) {
$("#main").append("<div class='pixel'></div>");
};
$(".pixel").last().append("</div>");
});
Two options - you can either initialize your hover event after creating the elements, or even better, you can use jQuery .on('mouseover') and .on('mouseout') and initialize the event before the elements are created:
$(document).on("mouseover", ".pixel", function() {
$(this).css("background-color", "yellow");
}).on("mouseout", ".pixel", function() {
$(this).css("background-color", "red");
});
$("body").append("<div id='main'>");
for (var i = 0; i < 256; i++) {
$("#main").append("<div class='pixel'></div>");
};
.pixel {
border: 1px solid #000;
display: inline-block;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or, the version still using the shorthand hover:
$("body").append("<div id='main'>");
for (var i = 0; i < 256; i++) {
$("#main").append("<div class='pixel'></div>");
};
$(".pixel").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "red");
});
.pixel {
border: 1px solid #000;
display: inline-block;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The issue is that you're appending the element you're trying to hover. Because it's not part of the DOM on page load, the event binding won't work the way you have it. Instead use:
$(document).ready(function(){
$("body").append("<div id='main'>");
for(var i=0; i<256; i++) {
$("#main").append("<div class='pixel'>Pixel</div>");
};
$(".pixel").last().append("</div>");
});
// Change BG on hover
$(document).on({
mouseenter: function(){
$(this).css("background-color", "yellow");
},
mouseleave: function(){
$(this).css("background-color", "red");
}
}, '.pixel');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

what is the best way to return the orginal style when mouseleave jquery?

I use mouseenter to input a new html. I face a challenge that I need to return the original style when mouse leave? When mouseleave, I need to remove the new html and use the original html What is the best way to do that?
var eye_disease1 = $('#eye_disease1');
eye_disease1.mouseenter(function () {
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
// what should I put here to return the original
});
Get the original HTML of eye_disease1 before changing and after mouse leave update HTML.
var eye_disease1 = $('#eye_disease1'),
diseaseHtml = '';
eye_disease1.mouseenter(function () {
if (!diseaseHtml) {
diseaseHtml = eye_disease1.html();
}
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
diseaseHtml = '';
eye_disease1.html(diseaseHtml);
});
You can all use the addClass
`$("selector").mouseenter(function(){
$(this).addClass("active");
})
$("selector").mouseleave(function(){
$(this).removeClass("active");
})`
var eye_disease1=$('#eye_disease1');
var eye_disease1_html;
eye_disease1.hover(
function() {
eye_disease_1_html = eye_disease1.html();
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>')
.fadeOut(0)
.css('border','none')
.fadeIn(400);
}, function() {
eye_disease1.find('span.show_li, span.show_li_2')
.fadeOut(400)
.delay(400)
.html(eye_disease1_html)
.fadeIn(0);
}
);
But yeah I would prefer to have all the content inside (original, and the hovered content) there the whole time.
HTML:
<div id="eye_disease1">
<div class="original-content">
Original Content
</div>
<div class="hovered-content">
<span class="show_li">symptoms</span>
<span class="show_li_2">diseases</span>
</div>
</div>
CSS:
.hovered-content {
display: none;
}
.hovered {
border: none;
}
JS:
$('#eye_disease1').hover(
function() {
$(this).addClass("hovered");
$(this).find(".original-content").fadeOut();
$(this).find(".hovered-content").fadeIn();
}, function() {
$(this).removeClass("hovered");
$(this).find(".hovered-content").fadeOut();
$(this).find(".original-content").fadeIn();
}
);
You can see it here: https://jsfiddle.net/waga7Lu1/3/
The transition effect is a bit clumsy but I'm not really sure what you're after.

Jquery, changing color on hover

This has been driving me crazy for a while, I cannot figure out what I am doing wrong. I am trying to make a 4x4 grid and change the color of each square when I hover my mouse over (the color stays after the mouse leaves) but the changing color part is not working.
Here is what I have so far:
Changing color on hover:
This is the part where I am stuck
$('.square').hover(function () {
$(this).addClass('hover');
});
You can remove your jquery code for adding class hover and just make this css change in the file
.square:hover {
background-color: red;
}
simply fixes your problem in pure Css.
Adding JsFiddle for this
http://jsfiddle.net/jjeswin/nb3dB/1/
You need to first call makeGrid(4); and then bind the event.
also to remove class you need to modify hover function to use mouseenter and mouseleave function:
makeGrid(4);
$('.square').hover(function() {
$(this).addClass('hover');
},function() {
$(this).removeClass('hover');
});
Working Demo
Update: for keeping the color even after mouseleave:
makeGrid(4);
makeGrid(4);
$('.square').hover(function() {
$(this).addClass('hover');
});
Demo with only mouseenter
I have updated the fiddle code http://jsfiddle.net/ZfKM8/5/
In your javascript, i've removed the hover function.
$(document).ready(function() {
function makeGrid(n) {
var grid = $('#container');
for (var i = 1;i<=n; i++) {
for (var j = 1; j <= n; j++){
grid.append("<div class='square'></div>");
}
grid.append("<div class='new_row'></div>");
}
};
makeGrid(4);
});
in your css, instead of .hover change it to .square:hover
.square:hover {
background-color: red;
}
$('#container').on("mouseenter", '.square', function() {
$(this).addClass('hover');
});
$('#container').on("mouseleave", '.square', function() {
$(this).removeClass('hover');
});
Use event delegation for dynamically created elements.
Demo:
http://jsfiddle.net/m6Bnz/1/
Use event delegation for added dom elements dynamically . it is the best way to do
$('#container').on('mouseenter' , ".square" , function() {
$(this).addClass('hover');
});
/* $('#container').on('mouseleave' , ".square" , function() {
$(this).removeClass('hover');
}); */
DEMO
here you go: http://jsfiddle.net/ZfKM8/3/
$(document).ready(function() {
function makeGrid(n) {
var grid = $('#container');
for (var i = 1;i<=n; i++) {
for (var j = 1; j <= n; j++){
grid.append("<div class='square'></div>");
}
grid.append("<div class='new_row'></div>");
}
};
makeGrid(4);
$(document).on('mouseenter','.square',function() {
$(this).addClass('hover');
});
$(document).on('mouseleave','.square',function() {
$(this).removeClass('hover');
});
});
Is there a specific reason why you're not using CSS for this?
.square:hover { color: #superAwesome }
If you want the color to animate (and delay when mousing out) you can use CSS3 transition:
.square { transition: color 1s; }
Try this
<html>
<head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<style>
.hover
{
background:red;
}
</style>
</head>
<body>
<div class="square" style="width:100px;height:100px;border:1px solid"> </div>
<script type="text/javascript">
$('.square').hover(function()
{
$(this).addClass('hover');
});
$('.square').mouseout(function()
{
$(this).removeClass('hover');
});
</script>
</body>
</html>
Since your boxes created dynamically to the DOM, the hover event will not be available for these boxes. In this case, event delegation will help you to attach that event
Try this
OP said the color stays after the mouse leaves
$('#container').on('mouseenter','.square',function() {
$(this).addClass('hover');
});
Make use of .toggleClass():
makeGrid(4);
$('.square').hover(function() {
$(this).toggleClass('hover');
});

Input text in field change background color of div

I want to have the div background color change colors only when there is text in the input field and when there is no text there the color doesn't change or it reverts back to the original color. Here is my code so far and it doesn't work.
<script type="text/javascript">
$(document).ready(function () {
$('#inputDatabaseName').change(function () {
$(this).parent().find('#colorchange').css('background-color','#ff0000');
$(this).css('background-color','#ff0000');
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="colorchange">
<input id="inputDatabaseName">
<table id="searchResults"><tr><td>empty</td></tr></table>
</div>
</form>
</body>
I'd suggest using classes instead of changing CSS attributes. This should work
$(function () {
$('#inputDatabaseName').keypress(function () {
var $this = $(this),
$div = $(this).parent(); // Cache the jQuery selectors to make code faster
if ($this.val().length > 0) {
$div.addClass("hasContent");
} else {
$div.removeClass("hasContent");
}
});
});
Now add some CSS:
#colorchange { background-color: white } /* default color */
#colorchange.hasContent { background-color: red } /* updated color */
#colorchange #inputDatabaseName { background-color: white } /* default color */
#colorchange.hasContent #inputDatabaseName { background-color: red } /*updated color*/
You can do it with this javascript
$('#inputDatabaseName').change(function () {
if($(this).val() ==="") {
$(this).parents('#colorchange').css('backgroundColor','red');}
else {
$(this).parents('#colorchange').css('backgroundColor','green');
}
});
You seem to be targeting the wrong element
Your selector is supposed to be
$(this).parent('#colorchange')
$(this).parent() points to div id="colorchange">
And you are trying to find again which will search its children
And use keyup event instead of the change if you want the change to be reflected immediately.
Also ID is supposed to be unique on the page.
So $('#colorchange').css( should do.
$(document).ready(function () {
$('#inputDatabaseName').keyup(function () {
var $this = $(this);
$colorDiv = $('#colorchange');
defaultColor = 'initial';
// If value is not empty assign a color
// otherwise this will be set to default.
if ($this.val() !== '') {
defaultColor = '#ff0000';
}
$('#colorchange').css('background-color', defaultColor);
$this.css('background-color', defaultColor);
});
});
Check Fiddle

Categories

Resources