jQuery selector for first row of inline-block divs - javascript

I have some divs with display: inline-block; and I have to select first row of divs and set them for example different border color and I need to do it in javaScript (jQuery).
Here is my example on jsFiddle
HTML :
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 5</div>
<div class="item">item 6</div>
<div class="item">item 7</div>
<div class="item">item 8</div>
<div class="item">item 9</div>
</div>
CSS :
.container {
border: 1px solid red;
padding: 10px;
}
.item {
display: inline-block;
border: 1px solid green;
width: 200px;
margin: 10px;
}
Is there a way how to do it?

You have to check what elements are in the first row, and mark those. A way to do this would be fiddle
This code makes the assumption that the first element is first in a row (which is always true), and checks which elements have the same offset top, it then applies a borderColor change to them
var top;
$('.container .item').each(function(i){
var thistop = $(this).offset().top;
if (i==0){
top = thistop;
}
if (top==thistop){
$(this).css({borderColor:"purple"});
}
});
Note that in a real life application you'd use a event handler on window resize to run this again on window resize.
I made a separate fiddle to do the event handler version. This requires wrapping above code in a function, and changing the functionality a bit to add/remove classes instead of just adding css (since adding and manually removing css get's messy). Fiddle can be found here.
So instead of adding css, it adds/removes a class
markrow = function(){
$('.container .item').each(function(i){
...
if (top==thistop){
$(this).addClass('special');
}else{
$(this).removeClass('special');
}
});
}
markrow();
$(window).on('resize',markrow);
With special being a css class that changes the border color
.special {
border-color:purple;
}

You may use vanilla CSS Selector for this in jquery.
Assuming that you have a grid of 3 X 3.
$( ".container .item:nth-child(3n + 1)" ).css( "border-color","black" );

$('.item').eq(0).addClass('special-border');
.special-border {
border-color: #00f;
}
http://jsfiddle.net/8193xgfn/9/

you can get the width of your container which has a css-style named "container" by $(".container").width,
and then you can calculate how many divs can be put in the first row,and put it in a variable like firstrow_divNums.
now use $(".calculate").children() to get the child-divs,
finally use "for" loop from $(".calculate").children().eq(0) to $(".calculate").children().eq(firstrow_divNums) ,
and now you can do what you want like adding css-style to any elements.

Related

Add a style to a class onclick a button

I have these 3 Boxes with the same classes and a button:
function turnRedAndAddPadding() {
/* ??? */
}
.box {
border: 1px solid;
display: inline;
}
<button onclick="turnRedAndAddPadding();">Press</button>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
I want to add styles to the class .box when clicking on the button without adding a new class to the boxes. Basically, if you press the button, the class .box should get a red background color and a padding and all the elements that have this class should have the same. Is there an easy way in JavaScript to solve this problem?
Thanks in advance.
You don't really want to add properties to the existing class. What you should do is add a new class that contains those red/padding properties to each element's class list.
Toolkit
You need some way to "pick up" the elements for processing. Since you have more than one querySelectorAll is probably the go-to choice which will give you a static nodelist (rather than a live HTML collection that methods like getElementsByClassName give you which have some side-effects if you don't use them correctly.)
You'll want a way to iterate over the elements to the processing. There are a number of possibilities provided in that link but forEach is a good choice here.
You'll want a way to update the class list of each element in the iteration. The unsuprisingly-named classList has, among its methods, add which accepts a string of the CSS class you want to add.
Define a new class ("redpad" in this example) that can be used.
Finally, because you want to avoid inline JS in 2023, you should be using addEventListener which accepts a) an event type and b) the name of the function you want to call when that event is fired.
const button = document.querySelector('button');
const boxes = document.querySelectorAll('.box');
button.addEventListener('click', turnRedAndAddPadding);
function turnRedAndAddPadding() {
boxes.forEach(box => {
box.classList.add('redpad');
});
}
.box {
border: 1px solid;
display: inline;
}
.redpad {
background-color: red;
padding: 0.5em;
}
<button type="button">Press</button>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
Based on that post you could try something like this:
function turnRedAndAddPadding() {
stylesheet = document.styleSheets[0]
stylesheet.insertRule(".box { background-color: red; padding: 10px;}", 0);
}
.box {
border: 1px solid;
display: inline;
}
<button onclick="turnRedAndAddPadding();">Press</button>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
Hope it helps.
Some really useful documentation by W3 Schools talks about how to use getElementsByClassName which you can find here You can find about editing the padding as well from here via the padding property of each element.
Below I am finding all div's that have the class box. Then iterating over each of them and assigning the colour and padding. You can change this to your liking.
There are also many other properties that you can edit for each DOM element like divs!
function turnRedAndAddPadding() {
const collection = document.getElementsByClassName('box');
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = 'red';
collection[i].style.padding = '5px';
}
}
Just adding some javascript you can achieve your goal.
document.querySelectorAll with this you can collect all elements with class box and then loop with a foreach function
function turnRedAndAddPadding() {
let box = document.querySelectorAll('.box');
box.forEach(el => {
el.style.background = 'red';
el.style.padding = '20px'
})
}
.box {
border: 1px solid;
display: inline;
}
<button onclick="turnRedAndAddPadding()">Press</button>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>

Get the elements that are overflowing

Is there anyway to find the elements that are overflowing outside of the div?
So you can edit them somehow, using JQuery for example?
I am trying to make it with an HTML table at the moment.
Check the javascript code to verify element is overflowing. This operation on large elements may be expensive.
const p = document.querySelector('.parent');
console.log('Overflow ' + (p.offsetHeight < p.scrollHeight));
.parent{
height: 50px;
border: 1px solid;
}
.child {
height: 20
}
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
</div>

Jquery selector - how can I ensure this works?

I have some buttons, labelled logo1 - logo15 respectively.
There is another button called 'lets-go' that fires a function based on these buttons being selected - when you click a logo the class 'active'.
When there is no logo selected, I would like this button to not be in the DOM - and be hidden. At the moment, the 'active' class for the button brings it's opacity to 1.
I have this jquery statement at the moment.
if (!$('.logo1, .logo2, .logo3, .logo4, .logo5, .logo6, .logo7, .logo8, .logo9, .logo10, .logo11, .logo12, .logo13, .logo14, .logo15').hasClass("active")) {
$('#lets-go').removeClass('active')};
But it's not working.
This is an example of one of my logoX buttons:
$('.logo15').on('click', function(e) {
$('.logo15').toggleClass("active");
$('#b15').toggleClass('alive');
$('#b15').toggleClass('zoomTarget');
$('#b15').toggleClass('dead');
$('#lets-go').addClass('active');
$('#popoutLetsGo').addClass('expand');
$('.instructions-arrow-2').addClass('hide')
});
On click, they apply the class of 'active' to let's go. But it doesn't remove it, ever. Just if you click any of the 15 buttons a new button appears, but if you deselect the button it's still there - and then the next screen is blank.
Can you see why it's not?
I am basically looking for: If none of these classes have the class of active, then make sure this id doesn't have the class of active either.
Consider the following:
if (!$("[class*='logo']").hasClass("active")) {
$('#lets-go').removeClass('active')};
}
This looks at the Class attribute for a item starting with "logo", so .logo3 would be one of those elements. But you may want to test each one.
$("[class*='logo']").each(function(i, el){
if(!$(el).hasClass("active")){
$('#lets-go').removeClass('active')};
}
});
See More:
https://api.jquery.com/attribute-contains-selector/
https://api.jquery.com/each/#each-function
You can also use simplified classes to help group selectors. Consider the following.
$(function() {
$(".logo").click(function() {
$(".logo.active").removeClass("active");
$(this).addClass("active");
$("#letsgo").prop("disabled", false);
});
$("#letsgo").prop("disabled", true);
})
.logo {
padding: .4em;
border: 1px solid black;
border-radius: 3px;
margin: 3px;
background: #eee;
color: #999;
}
.active {
background: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Make a Selection</p>
<div class="logo item-1">Logo 1</div>
<div class="logo item-2">Logo 2</div>
<div class="logo item-3">Logo 3</div>
<div class="logo item-4">Logo 4</div>
<div class="logo item-5">Logo 5</div>
<button id="letsgo">Let's Go!</button>

How to find the boundary of child Divs

Im trying to right align the Title on top of the last Div. As per the below image , the text should be on top of "Hello 5 / 4 / 3". When we resize the window button will float which is working and the text should be always be on top of the last button.
Unsure why the wrapper div is adding extra space to the right of the button and not aligning to the edge of the right most div. Extra space is coming even if the Title is not there , any insights about Div width calculation would be great.
I tried calculating the number of buttons in the top row using javascript and added offset to the title , but it seems tedious and not aligning at certain resolution.
http://jsbin.com/nonexegiqa/embed?html,css,console,output
HTML
<div class="wrapper">
<div class="title">Title</div>
<div class="clear"/>
<div class="btn">Hello 1</div>
<div class="btn">Hello 2</div>
<div class="btn">Hello 3</div>
<div class="btn">Hello 4</div>
<div class="btn">Hello 5</div>
<div class="btn">Hello 6</div>
<div class="clear"/>
</div>
CSS
.wrapper{
border:solid gray 1px;
}
.btn{
width:96px;
height:46px;
float:left;
border:solid gray 1px;
margin-left : 11px;
margin-bottom : 11px;
text-align:center;
}
.title{
float:right;
}
.clear{
clear:both;
}
You need to find count of .btn in first row when page resizing, Then set position of .title to last .btn in first row.
$(window).on("resize", function(){
var parWidth = $(".wrapper").innerWidth();
var chiWidth = $(".wrapper .btn").first().outerWidth(true);
var childCount = 0;
while(parWidth >= chiWidth){
parWidth -= chiWidth;
childCount ++;
}
var left = $(".btn:eq("+(childCount-1)+")").position().left;
$(".title").css("margin-left", left);
});
To better understanding, i create demo but because you can't change demo page size in here, i create it in JSFiddle.
yes, display:flex may be very helpful. As a work around you could set the width of the .wrapper to 70vw, or something similar. The .wrapper div width is creating the "extra space."

mousenter and mouse effect not working properly

Consider this JSFiddle
When I mouseenter on Span1 , a blue bar should appear below the Span1 (same for Span2 and Span3)
But even I mouseenter on Span1 or Span2 or Span3 , blue bar appears only under Span2.
CSS
div.demo {
display:table;
width:100%;
}
div.demo div {
display:table-cell;
text-align:center;
}
.under {
width:100px;
height:2px;
background-color:blue;
margin:0px auto;
display:block;
}
HTML
<div class="demo">
<div id='span1'>Span 1</div>
<div id='span2'>Span 2</div>
<div id='span3'>Span 3</div>
</div>
<div class="demo">
<div><span id='Span1'></span></div>
<div><span id='Span2'></span></div>
<div><span id='Span3'></span></div>
</div>
JS
$(document).ready(function(){
$('#span1').mouseenter(function(){
$('#Span1').addClass('under');
});
$('#span2').mouseenter(function(){
$('#Span2').addClass('under');
});
$('#span3').mouseenter(function(){
$('#Span3').addClass('under');
});
$('#span1').mouseleave(function(){
$('#Span1').removeClass('under');
});
$('#span2').mouseleave(function(){
$('#Span2').removeClass('under');
});
$('#span3').mouseleave(function(){
$('#Span3').removeClass('under');
});
});
You have no width on the cells before the hover
Working JSFiddle here: http://jsfiddle.net/F2smc/5/
div.demo div {
display:table-cell;
text-align:center;
width: 33%; // <<< Added this
}
Basically the other 2 cells are zero width so the second row collapses to something very narrow in the middle so it looks like it is only under option 2.
Better example: http://jsfiddle.net/F2smc/29/
You can get the same effect, without specifying an exact % width, by simply adding this CSS instead for the spans (so they do not collapse within their parent divs):
div.demo span
{
width:100%;
}
If you put unique colors on the divs it will become really obvious what is going on. 100% on the div does not mean the divs will use it like in a table. Basically any change that applies a width to the underlining divs/spans will work. Suggest you use Chrome in F12 debug mode to view this type of work as it clearly shows the original elements were all 0 width.
PS. Is really is a bad idea to use ids that vary only in case
On a separate note:
You would not normally hardwire events for each different id in JQuery when they all do roughly the same thing. If you change your ids to be really unique (not just by case) you can do something like:
$(document).ready(function () {
$('.menu').hover(function () {
$('#' + this.id + '-l').addClass('under');
}, function () {
$('span').removeClass('under');
});
});
Which takes the id of the current hovered item, appends something unique then updates the matching item by id.
Working demo: http://jsfiddle.net/F2smc/30/
That should clean things up while retaining your original structure.
For testing i have given text-decoration,you replace that with background-color..
HTML
<div class="demo">
<div id='one' class="hover">Span 1</div>
<div id='two' class="hover">Span 2</div>
<div id='three' class="hover">Span 3</div>
</div>
<div class="demo">
<div><span id='Span1'></span></div>
<div><span id='Span2'></span></div>
<div><span id='Span3'></span></div>
</div>
CSS
div.demo {
display:table;
width:100%;
}
div.demo div {
display:table-cell;
text-align:center;
}
.under {
width:auto;
height:1px;
text-decoration:underline;
margin:0px auto;
display:block;
}
JQuery
$(document).ready(function(){
$('.hover').hover(function(){
var id=$(this).attr("id");
$('#'+id).addClass('under');
},function(){
$('.hover').removeClass('under');
});
});
Working DEMO
Try this
I have editted your html and css
<div class="demo">
<div id='span1'>Span 1</div>
<div id='span2'>Span 2</div>
<div id='span3'>Span 3</div>
</div>
<div class="demo">
<span id='Span1'></span>
<span id='Span2'></span>
<span id='Span3'></span>
</div>
and add this to your css
div.demo span {
display:table-cell;
width:100px;
}
or
Try this
Working DEMO
without changing any html and css
just add width:100px; to
div.demo div {
display:table-cell;
text-align:center;
width:100px;
}
Hope this helps,thank you

Categories

Resources