How to change CSS property using JavaScript - javascript

I want to change a CSS property of a class using JavaScript. What I actually want is when a <div> is hovered, another <div> should become visible.
.left,
.right {
margin: 10px;
float: left;
border: 1px solid red;
height: 60px;
width: 60px
}
.left:hover,
.right:hover {
border: 1px solid blue;
}
.center {
float: left;
height: 60px;
width: 160px
}
.center .left1,
.center .right1 {
margin: 10px;
float: left;
border: 1px solid green;
height: 60px;
width: 58px;
display: none;
}
<div class="left">
Hello
</div>
<div class="center">
<div class="left1">
Bye
</div>
<div class="right1">
Bye1
</div>
</div>
<div class="right">
Hello2
</div>
When hello1 div is hovered, bye1 div should be visible and similarly bye2 should appear when hello2 is hovered.

You can use style property for this. For example, if you want to change border -
document.elm.style.border = "3px solid #FF0000";
similarly for color -
document.getElementById("p2").style.color="blue";
Best thing is you define a class and do this -
document.getElementById("p2").className = "classname";
(Cross Browser artifacts must be considered accordingly).

// select element from DOM using *const*
const sample = document.getElementById("myid"); // using CONST
// or you can use *var*
var sample = document.getElementById("myid"); // using VAR
// change css style
sample.style.color = 'red'; // Changes color, adds style property.
// or (not recomended)
sample.style = "color: red"; //Replaces all style properties. NOT RECOMENDED

Use document.getElementsByClassName('className').style = your_style.
var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";
Use single quotes for JS strings contained within an html attribute's double quotes
Example
<div class="somelclass"></div>
then document.getElementsByClassName('someclass').style = "NewclassName";
<div class='someclass'></div>
then document.getElementsByClassName("someclass").style = "NewclassName";
This is personal experience.

Consider the following example:
If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.
document.getElementById("ele_id").style.color="blue";
But, for changing multiple properies the more robust way is using Object.assign() or, object spread operator {...};
See below:
const ele=document.getElementById("ele_id");
const custom_style={
display: "block",
color: "red"
}
//Object.assign():
Object.assign(ele.style,custum_style);
Spread operator works similarly, just the syntax is a little different.

Just for the info, this can be done with CSS only with just minor HTML and CSS changes
HTML:
<div class="left">
Hello
</div>
<div class="right">
Hello2
</div>
<div class="center">
<div class="left1">
Bye
</div>
<div class="right1">
Bye1
</div>
</div>
CSS:
.left, .right{
margin:10px;
float:left;
border:1px solid red;
height:60px;
width:60px
}
.left:hover, .right:hover{
border:1px solid blue;
}
.right{
float :right;
}
.center{
float:left;
height:60px;
width:160px
}
.center .left1, .center .right1{
margin:10px;
float:left;
border:1px solid green;
height:60px;
width:58px;
display:none;
}
.left:hover ~ .center .left1 {
display:block;
}
.right:hover ~ .center .right1 {
display:block;
}
and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

This is really easy using jQuery.
For instance:
$(".left").mouseover(function(){$(".left1").show()});
$(".left").mouseout(function(){$(".left1").hide()});
I've update your fiddle:
http://jsfiddle.net/TqDe9/2/

You can do so using jQuery like this.
$('.left, .right').on('mouseenter', function(e) {
if ($(this).attr('class') == 'left1') {
$('.left1').css({
/* 'visibility': 'visible', */
'display': 'block',
})
} else if ($(this).attr('class') == 'left1') {
$('.right1').css({
/* 'visibility': 'visible', */
'display': 'block',
})
}
})
or you can use it like this
for first requirement
$('.left').on('mouseenter', function(e) {
$('.left1').css({
/* 'visibility': 'visible', */
'display': 'block',
})
})
for second requirement
$('.right').on('mouseenter', function(e) {
$('.right1').css({
/* 'visibility': 'visible', */
'display': 'block',
})
})

Related

How do i toggle between multiple classes for multiple elements in jQuery?

So I'm trying to implement a set of functions on my website with multiple div objects in it, so that when I click on Div A, it sets the text color of the page to red through Class A, and when i click on Div B, it sets the text to green through Class B, and so on and so forth.
My issue is that the other classes don't unset when clicking multiple objects and one class overrides the others, so the color of the text won't switch anymore.
I've been looking for solutions and trying to use addClass() and removeClass(), but it doesn't work for some reason. Here is a snippet of my code here
$(function() {
$('.one').click(function() {
$("h1").addClass('onetxt');
$("h1").removeClass('twotxt, threetxt');
});
});
$(function() {
$('.two').click(function() {
$("h1").addClass('twotxt');
$("h1").removeClass('onetxt, threetxt');
});
});
$(function() {
$('.three').click(function() {
$("h1").addClass('threetxt');
$("h1").removeClass('onetxt, twotxt');
});
});
h1 {
text-align: center;
}
div {
height: 65px;
width: 65px;
margin: 20px auto;
border-style: solid;
}
/*style info, ignore above here*/
.one {
background-color: red;
}
.onetxt {
color: red;
}
.two {
background-color: green;
}
.twotxt {
color: green;
}
.three {
background-color: blue;
}
.threetxt {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Sample Text</h1>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
Any help on this would be greatly appreciated, and if you need more info, ask me in the replies, thank you!
EDIT: Here's a JSFiddle link demonstrating the code that i currently have, my intention is for all three of the DIV elements to change the top text's color when selected in any order, with using the classes if possible.
It seems like the main issue is that removeClass doesn't support multiple class selectors (like 'onetxt, twotxt'). Also you aren't removing all possible classes depending on the order of clicks.
Here's a solution that might work. I've written some helper functions which hopefully clarify what's going on.
const targets = 'h1, p'
const classmap = {
one: 'onetxt',
two: 'twotxt',
three: 'threetxt'
}
const allclasses = Object.values(classmap);
function clearSelection() {
allclasses.forEach(function(clz) { $(targets).removeClass(clz) });
}
function addSelection(sel) {
$(targets).addClass(classmap[sel]);
}
$(function() {
$('.one').click(function(){
clearSelection();
addSelection('one')
});
});
$(function() {
$('.two').click(function(){
clearSelection();
addSelection('two')
});
});
$(function() {
$('.three').click(function(){
clearSelection();
addSelection('three')
});
});
Here's a vanilla DOM API solution based on classList.toggle(className: string, force: boolean). The second parameter controls whether toggle works as remove or add.
const classes = ['one', 'two', 'three'];
classes.forEach(clazz => {
document.querySelector(`.${clazz}`).addEventListener('click', () => {
classes.forEach(cl => document.querySelector('h1').classList.toggle(`${cl}txt`, cl === clazz));
})
})
h1 {
text-align: center;
}
div {
height: 35px;
width: 35px;
margin: 5px auto;
border-style: solid;
}
/*style info, ignore above here*/
.one {
background-color: red;
}
.onetxt {
color: red;
}
.two {
background-color: green;
}
.twotxt {
color: green;
}
.three {
background-color: blue;
}
.threetxt {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Sample Text</h1>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
There is no .removeClass() overload supports multiple argument, it only remove the first class. .removeClass() with no argument remove all the classes. This maybe the one you need.
I tweak your code a little bit, including:
Rename some class name. .color-palette is the container of all color selection. .color is individual color choice box.
Add data-color-name attribute to .color. The attribute will be used for sample-text css class assignment.
Simplify the click event with a single, event-delegate handler. I try to decouple the add/remove class logic with the actual color name. This way if you have more color boxes to add, you do not need to copy a new set of function.
Define custom css property. E.g. (--color-1, --color-2). The same property is used for color box background and sample text font color. You don’t have to maintain colors in two different place.
$('.color-palette').on('click', '.color', function(e) {
$("#sample-text").removeClass().addClass($(e.currentTarget).data('color-name'));
});
/* maintain the color choices here */
:root {
--color-1: red;
--color-2: green;
--color-3: blue;
}
h1 {
text-align: center;
}
.color {
height: 65px;
width: 65px;
margin: 20px auto;
border-style: solid;
}
/* style info, ignore above here */
/* color palette style */
.color.color-1 {
background-color: var(--color-1);
}
.color.color-2 {
background-color: var(--color-2);
}
.color.color-3 {
background-color: var(--color-3);
}
/* sample text style */
#sample-text.color-1 {
color: var(--color-1);
}
#sample-text.color-2 {
color: var(--color-2);
}
#sample-text.color-3 {
color: var(--color-3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="sample-text">Sample Text</h1>
<div class="color-palette">
<div class="color color-1" data-color-name="color-1"></div>
<div class="color color-2" data-color-name="color-2"></div>
<div class="color color-3" data-color-name="color-3"></div>
</div>

Show Hide Div if element class loaded

I want to show the div if another div class is loaded.
Show nanobar only if selected class is loaded, in other case nanobar will become hidden
css code sample:
.nanobar {
height: 75px;
width: 100%;
background: #fef9c7;
border:1px solid #fce181;
color:#333;
padding:10px;
margin-bottom:10px;
font-size: 1.2rem;
display:none;
}
HTML code sample:
<div class="nanobar">
<span>Content</span>
</div>
<div id="category_container" class="content-padding {if $category} selected{/if}"> </div>
any help in this regards will be appreciated.
The code checks if the second div has a selected class. If so, the first div will be displayed, otherwise the first div stays hidden.
let divElements = document.querySelectorAll('div');
if (divElements[1].classList.contains("selected")) {
divElements[0].classList.replace("hide", "show");
} else {
divElements[0].classList.replace("show", "hide");
}
.nanobar {
height: 75px;
width: 100%;
background: #fef9c7;
border:1px solid #fce181;
color:#333;
padding:10px;
margin-bottom:10px;
font-size: 1.2rem;
}
.hide {
display: none;
}
.show {
display: block;
}
<div class="nanobar hide">
<p>Hello</p>
</div>
<div class="apple jason selected hide">
<p>Jason</p>
</div>
Note: Removed the display property from nanobar class and made it into it's own class. Makes it easier to hide and show an element, as well as being able to reuse it for other elements.
You can read more about classList here
First check if you can find selected class:
var selected = document.getElementsByClassName("selected");
Then check if this variable has more then one element.
if (selected.length < 1) {
// Hide your nanobar
} else {
// Show it
}
This is not the full solution, if you still have troubles, ask in comments.

expand div on click Polymer js without jquery

I'm using Polymer but I'm having some trouble with events and the such. I want to create an expanding search bar, similar to
My current code looks something like the following:
Code:
// This is where things are a little unclear for me. So far, I have tried the following:
expand: function() {
var divToStretch = this.$.stretchMe;
if ( /*search bar is open*/ ) {
//remove "stretched" css from "stretch" div
} else {
//add "stretched" css to "stretch" div
}
}
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
.stretched {
width: 500px;
}
<div class="stretch" id="stretchMe">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
May I suggest a pure CSS alternative? You can make your search bar receive focus, by adding tabIndex="0". This way you can provide a style for div.stretch:focus, allowing you to dynamically change its size when the user clicks or focuses on the element and making it small again when the user focuses on something else.
It's really simple, elegant, does not need a lot of code and does what you need. Give it a try!
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
div.stretch:focus {
width: 500px;
}
<div class="stretch" id="stretchMe" tabIndex="0">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
Alternatively, you can make it do the same thing on :hover, if that's what you are after, simply by changing the selector. Or combine both, if you prefer. Below is a :hover example.
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
div.stretch:hover {
width: 500px;
}
<div class="stretch" id="stretchMe">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
You can use the toggle method of the classList for this:
expand : function() {
this.$.stretchMe.classList.toggle('stretched');
}
The classic way would be as following:
if (/*search bar is open*/) {
divToStretch.style.width = "auto";
} else {
divToStretch.style.width = "500px";
}
But I highly recommend using this.$.stretchMe.classList.toggle('stretched');
Read more here

Resizing one element using jQuery UI changing the position of another

I am trying to make resizible and draggable lines out of labels using jQuery UI.
The problem is, if I add two labels and try to resize the first label, it changes the position of the second label (but if I resize the second label it does not change the position of the first label).
How to prevent labels from changing other label's position while resizing..?
HTML:
<div id="main">
<button id="s">add line</button>
</div>
<div id="line" class="hidden">
<label class="dra"></label>
</div>
JS:
function makeline() {
$t = $(".dra", "#line").clone(true).draggable().resizable({
handles: "s, n"
});
$("#main").append($t);
}
$("#s").click(function () {
makeline();
});
CSS:
.dra {
display: block;
background-color:red;
width: 7px;
height: 80px;
border: 1px solid red;
}
.hidden {
display: none;
}
#main {
border: 1px solid black;
width:500px;
height: 300px;
}
UPDATE: Full code in JSFiddle
This is happening because the jQuery UI widgets set the position of element to relative by default, leaving it in the normal flow of the document. You can work around this issue by applying position:absolute for the elements like:
.ui-resizable {
position:absolute !important;
}
This will cause them to stack on top of each other rather than one below another since they aren't in the normal flow anymore. You can easily fix this using the jQuery ui position() utility method as shown below:
$("#s").click(function() {
$t = $("#line .dra").clone(true).draggable().resizable({
handles: "s, n"
})
if ($("#main").find(".dra").length) {
$t.position({
at: "left bottom",
of: "#main .dra:last"
})
};
$("#main").append($t);
});
.dra {
display: block;
background-color: red;
width: 7px;
height: 80px;
border: 1px solid red;
}
.hidden {
display: none;
}
#main {
border: 1px solid black;
width: 500px;
height: 300px;
}
.ui-resizable {
position: absolute !important;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div class="form-group">
<label>ADD two line and RESIZE THE FIRST LINE it will scroll down the line added after it. NOW add a 3rd line and resize the second line it will scroll down the 3rd line and if you resize the very first line you added it will scroll down the other lines</label>
<div id="main">
<button id="s">add line</button>
</div>
<div id="line" class="hidden">
<label class="dra"></label>
</div>
You can adjust the positioning however you want.
If your label is:
<div class="label">Lorem ipsum</div>
add this CSS:
.label {
white-space: nowrap;
}

Can't Use :not() Selector

I am trying to make a Tic-Tac-Toe game and I am currently working on the aspect of selecting the boxes themselves, but while using JQuery the :not selector doesn't seem to be working.
function main(){
//Functions
$('.cell:not(.block)').click(function(){
$(this).addClass(color);
$(this).addClass('block');
if(color=='g'){color='r';}else{color='g';}
});
//Variables
var color = 'g';
}
$().ready(main);
html {
background-color:black;
color:white;
text-align:center;
}
.cell {
border: 1px solid white;
margin:1px;
width:30%;height:30%;
}
.g {background-color:lime;}
.r {background-color:red;}
#board {height:500px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>Tic Tac Toe</header>
<div id='board'>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
</div>
That isn't how jQuery selects elements.
When you run $('selector'), the selector is evaluated immediately, against the current state of the DOM. Your three elements are found because none of them have .block, and click handlers are bound to all three elements.
There are several ways of fixing this:
If you want the selector to be dynamically evaluated, you need to use on to delegate the event to one of the containing elements. The event on the specific child element will bubble up to the containing element's handler and be tested each time against the selector. This is the most expensive option, and probably the least desirable; you shouldn't be relying on jQuery selectors for this kind of logic:
$('.board').on('click', '.cell:not(.block)', function () {
// ...
});
Alternatively, the simplest and cheapest option is to simply check for .block in the click handler:
$('.cell').click(function () {
if ($(this).hasClass('block')) return;
//...
Finally, you can unbind the click handler at the same time you add the .block class
$('.cell').click(function () {
$(this).unbind( "click" );
// ...
Since you are changing the class after already have made the selection it would count as a dynamic selector and you need to use .on() for that.
function main() {
//Functions
$('#board').on('click', '.cell:not(.block)', function() {
$(this).addClass(color).addClass('block');
color = color == 'g' ? 'r' : 'g';
});
//Variables
var color = 'g';
}
$().ready(main);
html {
background-color: black;
color: white;
text-align: center;
}
.cell {
border: 1px solid white;
margin: 1px;
width: 30%;
height: 30%;
}
.g {
background-color: lime;
}
.r {
background-color: red;
}
#board {
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>Tic Tac Toe</header>
<div id='board'>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
</div>

Categories