For the HTML below, what is the best centralized way to replace using an inline onclick in each of the five siblings's children DIVs to set the background color red for whichever one gets clicked and clearing all others?
The inline approach to be replaced:
<div id="tab1" onclick="setRed();">tab 1</div>
Leaving cleaner markup:
<div>tab 1</div>
This is how the whole thing should look:
<div id="nav">
<div class="blue"><div>tab 1</div></div>
<div class="blue"><div>tab 2</div></div>
<div class="blue"><div>tab 3</div></div>
<div class="blue"><div>tab 4</div></div>
<div class="blue"><div>tab 5</div></div>
</div>
This is the final solution, hobbling the select portion from user2865156 and adding some javascript to clear the rest:
$("#nav div div").on('click', function () {
if (this.style.backgroundColor !== "red") {
this.style.backgroundColor = "red";
siblingDivs = this.parentNode.parentNode.children;
for (var i = 0; i < siblingDivs.length; i++) {
if (this !== siblingDivs[i].children[0]) {
siblingDivs[i].children[0].style.backgroundColor = "transparent";
}
}
}
});
Try using something like this. You need to set it to the actual function instead of the value of the return value:
var divTabs = document.getElementById("nav").onclick = function() {
//do something here
}
If I understood your question, you may need to use the .each() method to get the index of the clicked element and add the corresponding red class to it, so
having this css
.red { background-color: #ff0000; }
You could use this jQuery script:
jQuery(document).ready(function ($) {
$(".blue").each(function (i) {
$(this).on("click", function () {
$(".blue").removeClass("red").eq(i).addClass("red")
})
})
}); // ready
Notice we are using the .eq(i) method to assign the red class to the clicked element after removing the same class from any other.
See JSFIDDLE
I think this is what you need.
DEMO
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding: 24px;
}
.blue {
cursor: default;
border: 1px dashed #454545;
padding: 8px 16px;
display: inline-block;
}
.blue.active {
background: red;
}
jquery js
$(function() {
$('#nav').on('click', '.blue', function(e) {
var $this = $(this),
innerHtml = $this.html(), //inner html
text = $this.text();
// there are obv easier ways to do the below; just a proof of concept.
!!~text.indexOf("tab") && $('.active').removeClass('active') &&
$this.addClass('active');
})
})
Using jQuery, target the class:
$("#nav .blue").click(function() {
//$(this) refers to the clicked element as a jQuery object
var innerHtml = $(this).html(); //inner html
var text = $(this).text(); //text inside the inner html
//Logic
});
Is this what you're trying to do?
http://jsfiddle.net/Lwex5wr4/
$(".blue").on('click', function() {
if (this.style.backgroundColor === "red") {
this.style.backgroundColor = "transparent";
} else {
this.style.backgroundColor = "red";
}
});
Try to do this:
$("#nav .blue").click(function() {
$(this).css('background-color', 'red');
});
Related
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>
To simplify my problem, I made a jsfiddle
When I click on "Click me" it displays a box, but when i click on it twice
at the same time, it displays two boxes at the same time, and for my case it should not be possible. The second box should be able to be displayed only if the first box is completly displayed and the user click again on 'Click me'.
How can I achieve that ?
$('#clickme').click(function() {
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
$div.show('clip', 3000);
});
#clickme {
cursor: pointer
}
.newDiv {
height: 40px;
width: 40px;
background-color: red;
margin: 5px;
display: none;
padding: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<a id="clickme">Click me</a>
<div id="container"></div>
A simple solution is to use a flag, to check the state whether action can be performed.
Here complete callback of .show() is used to reset the flag once effect is complete.
var disable = false;
$('#clickme').click(function() {
var elem = $(this);
if (disable == false) {
disable = !disable;
elem.toggleClass('none', disable);
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
$div.show('clip', 3000, function() {
disable = !disable;
elem.toggleClass('none', disable);
});
}
});
#clickme {
cursor: pointer
}
#clickme.none {
cursor: none
}
.newDiv {
height: 40px;
width: 40px;
background-color: red;
margin: 5px;
display: none;
padding: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<a id="clickme">Click me</a>
<div id="container"></div>
I think the cleanest solution is to bind and unbind your click handler. No need to use a flag or a timeout.
function clickHandler() {
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
// Unbind click handler until animation is completed
$("#clickme").off("click", clickHandler);
// Begin animation
$div.show('clip', 3000, function() {
// Animation completed. Bind click handler.
$("#clickme").on("click", clickHandler);
});
}
// Initial bind of click handler
$("#clickme").on("click", clickHandler);
Here's a working fiddle.
You can disable the button for the time when the box is being drawn. Like this:
$('#clickme').click(function() {
disabling the button for 3000 sec as the box takes 3000 sec to get rendered.
setTimeout(function(){
$(this).attr('disabled','disable');
},3000);
$(this).removeAttr('disabled');
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
$div.show('clip', 3000);
});
So you need to stop execution if the box is still being animated.
I am using the complete argument of jQuery.show method.
var inAnimation = false;
$('#clickme').click(function() {
if(inAnimation)
return;
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
inAnimation = true;
$div.show('clip', 3000, function() {inAnimation = false;});
});
i always use callback after end of animation:
let open = true;
$('#clickme').click(function(){
if ( open ) {
open = false;
$div = $('<div>',{"class" : "newDiv"});
$('#container').append($div);
$div.show('clip',3000, function(){
open = true;
});
}
});
fiddle
If you want a simple solution for your problem you can place an if statement before the assignment of the $div variable:
$('#clickme').click(function() {
if($('.newDiv').length == 0){
$div = $('<div>', {
"class": "newDiv"
});
$('#container').append($div);
$div.show('clip', 3000);
}
});
$('.newDiv').click(function() {
$('.newDiv').destroy();
}
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');
}
});
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.
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