Jquery change background colour for a selected div - javascript

I have this HTML code div in 4*4 format :
$(document).ready(function() {
$("div").click(function(e){
var id_val=this.id;
var word = id_val.split("-").pop();
alert(word)
e.preventDefault();
for(var i=1;i<=4;i++)
{
if(i!=word)
{
$("#div-"+i+"").css("background-color","white");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1">
<p>div1</p>
<div id="div-2">
<p>div2</p>
<div id="div-3">
<p>div3</p>
<div id="div-4">
<p>div4</p>
</div>
</div>
</div>
</div>
I have written the jquery code when on click the particular div has to change colour to red and remaining div colour should be white
When I have executed this only the div1 has changing the colour to red and other divs are not changing the colour.
for eg :
if I click div1 change to red colour and other div2,div3,div4 should be in white
color
If I click div2 change to red colour and other div1,div3,div4 should be in white
color

You need to use e.stopPropagation(); to prevent the other div elements from triggering as well.
you didn't properly terminate the first two lines with }); at the end of the script.
$(document).ready(function() {
$("div").click(function(e) {
var id_val = this.id;
var word = id_val.split("-").pop();
if (word != null) {
alert(word)
e.stopPropagation();
for (var i = 1; i <= 4; i++) {
if (parseInt(i) === parseInt(word)) {
$("#div-" + i + "").css("background-color", "red");
} else {
$("#div-" + i + "").css("background-color", "white");
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div-1">
<p>div1</p>
<div id="div-2">
<p>div2</p>
<div id="div-3">
<p>div3</p>
<div id="div-4">
<p>div4</p>
</div>
</div>
</div>
</div>

Try something Like that
$("div").click(function(e){
$("div[id^='div-']").css("background-color","white");
$(this).css("background-color","red");
}

You need to use e.stopPropagation() and not e.preventDefault(). Also since divs are nested you should give a color to the inside p tag and not the div itself. Also terminate your function correctly.
$(document).ready(function() {
$("div").click(function(e){
var id_val=this.id;
$(this).first("p").css("background-color","red")
var word = id_val.split("-").pop();
alert(word)
e.stopPropagation();
for(var i=1;i<=4;i++)
{
if(i!=word)
{
$("#div-"+i+"").css("background-color","white");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1">
<p>div1</p>
<div id="div-2">
<p>div2</p>
<div id="div-3">
<p>div3</p>
<div id="div-4">
<p>div4</p>
</div>
</div>
</div>
</div>

This worked for me
$("div").click(function (e) {
$(this).css("background-color", "red");
$('div:not(#' + this.id + ')').css("background-color", "white");
e.stopImmediatePropagation();
});

Try to use this simple code
$(document).ready(function() {
$("div").click(function(e) {
$('div[id^="div-"] p').css("background-color", "white"); //change the remaining elements who's id start with div- color to white
if ($(e.target).is('p')) {
$(e.target).css("background-color", "red"); //change the clicked element color
}
});
});
$("div").click(function(e) {
$('div[id^="div-"] p').css("background-color", "white"); //change the remaining elements who's id start with div- color to white
if ($(e.target).is('p')) {
$(e.target).css("background-color", "red"); //change the clicked element color
}
});
body {
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1">
<p>div1</p>
<div id="div-2">
<p>div2</p>
<div id="div-3">
<p>div3</p>
<div id="div-4">
<p>div4</p>
</div>
</div>
</div>
</div>

Related

How to select element with specific class in a container

<section class="refinementsContainer">
<div class="contentfilters">
<div class="refinementContainer refinementmicro" data-dimension="micro"></div>
<div class="refinementContainer refinementcolor" data-dimension="color"></div>
<div class="rightContainer">
<div class="refinementContainer sort"></div>
<div class="refinementContainer refinementSeason"></div>
</div>
</div>
</section>
I have this code. I need to append one class at only one div into the div with class contentfilters. I develop this code but it doesn't work:
$buttonOpenFilter.on(clickEvent, function(e) {
e.stopPropagation();
e.preventDefault();
var $this = $(this).parent();
var classOpen = 'open';
if ($this.hasClass(classOpen)) {
$this.removeClass(classOpen).css('max-height', 30);
} else {
$this.siblings().removeClass(classOpen).css('max-height', 30);
$this.addClass(classOpen).css('max-height', $this.find('ul').height() + 105);
}
});
$('.contentfilters')
https://api.jquery.com/category/selectors/ here you will find everything about selectors.

Two clicks - different actions (same div)

Hope someone could help!
I have some divs (using bootstrap) like:
<div class="container">
<div class="row" id="r2">
<div class="col-lg-8">
<div class="block-in-div"></div>
</div>
<div class="col-lg-4">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-4">
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
</div>
<div class="col-lg-8">
<div class="block-in-div"></div>
</div>
</div>
</div>
</div>
</div>
</div>
When I click on some div it should randomly get some background color.
When I click on another div, previous should reset its background, and newly clicked div should get its random background.
Whith this issues everything is clear.
I can`t get how to do next: I clicked on div, it changes its colour, I click again and it should become bigger.
Color randomizer:
function getRandomColor() {
var r=Math.floor(Math.random() * (256));
var g=Math.floor(Math.random() * (256));
var b=Math.floor(Math.random() * (256));
var color = '#' + r.toString(16) + g.toString(16) + b.toString(16);
return color;};
Reset background:
function cancelBg() {
let selectedBlocks = $("div.block-in-div");
$.each(selectedBlocks,function(key,value){
selectedBlocks[key].style.background = "none";
});};
Main function:
$(document).ready(function () {
$(".block-in-div").click(function () {
cancelBg();
$(this).css("background", getRandomColor());
});});
Trying smth like:
$(document).ready(function () {
$(".block-in-div").click(function () {
var state = 1;
return function () {
cancelBg();
if(state===1){
$(this).css("background", getRandomColor());
state=2;
}
else if(state===2){
/*$(this).addClass("active");*/
state=1;
}
};
}());});
.active just for test and it is simply:
.active{
height: 100vh;
width: 100vw;
}
Please help!
Be the force with you! :)
You can achieve this by adding a class when the div was clicked first.
$(document).ready(function () {
$(".block-in-div").click(function () {
return function () {
cancelBg();
if(!$(this).hasClass('not-resized')) {
$(this).css("background", getRandomColor());
$(this).addClass('not-resized');
}
else if ($(this).hasClass('not-resized')) {
$(this).addClass("active");
$(this).removeClass('not-resized');
}
};
}());
});
If you need to reset the state on click on other div you can just add $(".block-in-div").removeClass('not-resized'); at the end.
Note 1: Adding active class like you did will have lower priority than the size on original class (add an !important as a temporal fix to see the changes or even better... make a stronger selector).
Note 2: If I didn't get the requirements right pls. tell me.
Thanks everyone!
Mold something like JSFiddle
$(document).ready(function () {
$(".block-in-div").click(function () {
if($(this).hasClass('tofull') && !$(this).hasClass('active')){
$(this).addClass("active");
}
else if($(this).hasClass('active')){
$(this).removeClass("active tofull");
$(this).css("background", "none");
}
else{
cancelBg();
let clr = "#"+((1<<24) * Math.random()|0).toString(16);
$(this).css("background", clr);
$(this).addClass("noColor tofull");
}
});
});
Still got some problems with working but got ideas how to fix it.
Problem is: Click block A (become red), click B (yellow), click C (green), click A again - size changes but no background

How to select a row that has been clicked

I want have a list of items in which the color of a selected element turns red when it is selected and all of the other divs turn blue. How can I identify the selected div that would then turn red?
$(document).ready(function() {
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className = "blueText";
}
//Set the style for tyhe selected div
//selectedItem.className="selectedText";
});
});
.selectedText {
color: red;
}
.blueText {
color: blue;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div>
Line 2
</div>
<div>
Line 3
</div>
</div>
</div>
</body>
</html>
It's enough to change:
//selectedItem.className="selectedText";
to:
event.target.className="selectedText";
The snippet:
$(document).ready(function(){
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className="blueText";
}
//Set the style for tyhe selected div
event.target.className="selectedText";
});
});
.selectedText {
color: red;
}
.blueText {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div >
Line 2
</div>
<div >
Line 3
</div>
</div>
</div>
You can do it with this:
$('#table_1 .tableRow div').click(function() {
$(this).removeClass().addClass('selectedText').siblings().removeClass().addClass('blueText')
})
.selectedText {
color: red;
}
.blueText {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div>
Line 2
</div>
<div>
Line 3
</div>
</div>
</div>
Pure CSS solution using tabindex and :focus Selector for DIV's.
div:focus {
color: red;
}
div {
color: blue;
}
<div id="table_1" class="table">
<div class="tableRow">
<div tabindex="1">Line 1</div>
<div tabindex="2">Line 2</div>
<div tabindex="3">Line 3</div>
</div>
</div>
You can use the $(this) object to reference the element on which a jQuery handler was made:
$(document).ready(function(){
$('#table_1 .tableRow div').click(function(event) {
//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className="blueText";
}
$(this).addClass('selectedText')
});
});
Also, if you want to use something other than just the CSS class to determine if an element is selected or not (outside of the jQuery callback), you could add a data-* attribute to it 1.

How to avoid the particular class from applying css

My HTML
<body>
<div id="finalparent">
<!--many parent divs here-->
<div id="1stparent">
<div id="txt_blog_editor" class="box" style="width: 1097px;">
<div class="abc anotherclass">
</div>
</div>
</div>
</div>
<div class="abc"></div>
</body>
My Script
$('html').on('mouseover','.fr-bttn .fa-picture-o', function () {
var pos = $(this).offset();
console.log(pos.left+"||"+pos.top);
var left_pos=(pos.left-15)+"px";
var top_pos=(pos.top+35)+"px";
$(".abc").css({position: "absolute", top: top_pos, left: left_pos });
$(".abc").show();
$(".popup").show();
});
});
I want to apply the left and top to abc class which is without parent and not to the class which is under id="txt_blog_editor"
According to this answer here is a working snippet:
jQuery.expr[':'].noparents = function(a,i,m){
return jQuery(a).parents(m[3]).length < 1;
};
var elts = $(".abc").filter(":noparents(#txt_blog_editor)");
elts.css({ "background-color": "green" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="finalparent">
<!--many parent divs here-->
<div id="1stparent">
<div id="txt_blog_editor" class="box" style="width: 1097px;">
<div class="abc anotherclass">
ABC With Parent
</div>
</div>
</div>
</div>
<div class="abc">ABC WITHOUT Parent</div>
Basically, you create a new jQuery expression :noparents which returns elements not having selector given parents
You need to check if .abc has a parent #txt_blog_editor http://jsfiddle.net/ugv2pxdw/4/
$('html').on('mouseover','.fr-bttn .fa-picture-o', function () {
var pos = $(this).offset();
console.log(pos.left+"||"+pos.top);
var left_pos=(pos.left-15)+"px";
var top_pos=(pos.top+35)+"px";
$('.abc').each(function(){
if (!$(this).parents('#txt_blog_editor').length) {
$(this).css({position: "absolute",top: top_pos, left: left_pos });
$(this).show();
$(".popup").show();
}
});
});
If abc classes are only direct childs of body, why not using body > .abc as your selector?

Smooth css change transitions

I've setup a jQuery function that changes the body background colour when a certain div comes into view, e.g. the body background colour is black, when #block-three (that contains black text), the body background colour changes to white, and changes back when this goes out of view. This works fine, it's just very sudden though, I'm looking for a much smoother transition between background colours, fading between colours as you scroll (if possible).
jsFiddle demo: http://jsfiddle.net/neal_fletcher/TB53d/
HTML:
<div id="block-one" class="block">
<div class="inner-block">Test</div>
<div class="inner-block"></div>
<div class="inner-block"></div>
</div>
<div id="block-two" class="block">
<div class="inner-block">Test</div>
</div>
<div id="block-three" class="block">
<div class="inner-block">Test</div>
<div class="inner-block"></div>
</div>
<div id="block-four" class="block">
<div class="inner-block">Test</div>
<div class="inner-block"></div>
<div class="inner-block"></div>
</div>
<div id="block-five" class="block">
<div class="inner-block">Test</div>
<div class="inner-block"></div>
<div class="inner-block"></div>
</div>
jQuery:
var blockHeight = [];
$(".block").each(function () {
blockHeight.push($(this).height());
});
function hoverCurrentItem() {
var sIndex = 0;
var totalHeight = 0;
var scrolled = $(window).scrollTop();
for (var i in blockHeight) {
totalHeight += blockHeight[i];
if (totalHeight > scrolled) {
break;
} else {
sIndex++;
}
}
var $sItem = $(".block").eq(sIndex);
if (!$sItem.hasClass("selected")) {
$(".selected").removeClass("selected");
$sItem.addClass("selected");
}
if ($("#block-three").hasClass("selected")) {
$("body").css("background-color", "white");
} else {
$("body").css("background-color", "black");
}
}
hoverCurrentItem();
$(window).scroll(function (e) {
hoverCurrentItem()
});
Any suggestions would be greatly appreciated!
You could use transition with CSS:
body {
background-color: black;
transition:all 1s;
}
The Demo Fiddle

Categories