How to find all divs with specific ID using jQuery regular expression - javascript

In my document I've got several divs with ID beginning with letter "p" and then any number. I'd like to find them all using jQuery regular expression pattern and then add class to them. Can you help me fix this snippet? Thanks.
$(function(){
var pattern = "#p\d+";
$(pattern).addClass(".red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="p46"></div>
<div id="p124"></div>

Sure, you can use the filter method to apply any specific logic you need:
$(function(){
$("div")
.filter(function() { return /^p\d+$/.test(this.id); })
.addClass("red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="nomatch"></div>
<div id="p124"></div>

You could try
$("div").filter(function(i,e){return e.match(/^p\d+$/)!=null;}).addClass("red")
It basically finds all divs, then filters out those that don't match the regular expression and adds the class to the remaining tags. (I have not tested this code.)

You can add classes this way:
$("div[id^='p']").addClass(".red");

Related

Hover on two elements using jQuery

I have two <div> elements attached to each other, I mean there is no space between them.
<div id="box1">1</div>
<div id="box2">2</div>
And I have this jQuery code:
$('#box1 , #box2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
My problem is when I move the mouse between box1 and box2, I still get on console log "Not".
I want those divs to be considered as one element so when I move the mouse between them I don't get on console log "Not".
Thanks in advance!
I want those divs to be considered as one element
Well, quite simply, they aren't. And they can't be. That's not how HTML and CSS works.
The hover event is triggered one for each individual element bound to the event handler. And every time you leave one of those elements it will print the "not" output as per your instructions.
There is no "fix" for this in the exact way you described, but there are alternative approaches. An obvious solution is to wrap them both in an outer div and bind the hover event to that instead. Then the whole area will be considered as one element (because it literally is). Demo:
$('#boxcontainer').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
#boxcontainer {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxcontainer">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
friend check the code below. I think it will work for you. As you have dai you have an absolute position div you must need a parent div and the parent div position must be relative. For doing that you have to add just a simple CSS code position: relative;. You also need to do some changes to your jquery code. You can just hover on the parent div and it will do your work. Hope this code will help you.
//Box 1 Demo
$('#boxParrent1').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
//Box 2 Demo
$('#boxParrent2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
/*Main Code that are needed*/
#boxParrent1, #boxParrent2 {
position: relative;
}
/*Codes Just used to give you a demo*/
#boxParrent1, #boxParrent2{
display: flex;
margin-bottom: 50px;
border: 1px solid #000;
}
#boxParrent1{
width: 200px;
}
#boxParrent2{
width: 210px;
}
#box1, #box2, #box3, #box4{
background: tomato;
width: 100px;
height: 100px;
display: grid;
justify-content: center;
align-items: center;
font-family: Arial;
font-size: 50px;
color: #fff;
cursor: pointer;
}
#box2, #box4{
position:absolute;
top: 0;
left:100px;
background: #02dce6;
}
#box4{
left:110px;
background: #02dce6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxParrent1">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
<div id="boxParrent2">
<div id="box3">3</div>
<div id="box4">4</div>
</div>
Try to place your 2 div's in one super div
<div id="super">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
$('#super').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});

How to remove a class on second click in jQuery

Basically what I want to do is adding the .ani class to the clicked element and removing the .ani from all, but I also need to remove the .ani from the element which already have it on second click.
As you can see the regular add and removing is working fine but I can not remove the .ani on existing element. How can I fix this?
$(".list").on('click', function() {
$('.list').removeClass("ani");
if ($(this).hasClass('ani')) {
$(this).toggleClass("ani");
} else {
$(this).addClass("ani");
}
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
It looks like you are over complicating this task. Take a look at the code below (posting only the JS as HTML and CSS are the same):
$(".list").on('click', function() {
$(this).toggleClass("ani").siblings().removeClass("ani");
});
A breakdown of what this does:
use toggleClass on the item clicked to add remove the class on the
item
get all siblings of the clicked item and remove the class from them
How this works:
The bit of code in the example above uses something called method chaining where you execute multiple methods on the same jQuery Object. This is possible because most jQuery methods return a jQuery Object, post-execution. This makes it easier and faster to run a bunch of operations on the same set of elements. One thing that you need to be mindful about when chaining is the sequence of method calls - changing the order of methods that you use may result in adverse effects (i.e: most traversal methods in jQuery returns a different set of elements).
Fiddle: http://jsfiddle.net/darshanags/kz2wdo09/
Check this one. Just update onclick method. All other code is the same. I posted one is single line code and one if-else code which is commented. You can use which one is more comfortable for you. You are first removing ani class that was a bug in your code.
$(".list").on('click', function() {
$(this).toggleClass("ani").siblings().removeClass("ani");
/*if($(this).hasClass("ani")){
$(".list").removeClass("ani");
} else {
$(".list").removeClass("ani");
$(this).addClass("ani");
}*/
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
In this code:
$(".list").on('click', function() {
$('.list').removeClass("ani");
if ($(this).hasClass('ani')) {
$(this).toggleClass("ani");
} else {
$(this).addClass("ani");
}
});
You're removing the class of every .list element, therefore the $(this).hasClass('ani') will always be false (you just removed the ani class of every single .list element, including the clicked one), so the line $(this).addClass("ani") will always be executed.
The solution is simple. Check if the clicked element has the ani class and if so, remove it, otherwise add it:
$(".list").on('click', function() {
if ($(this).hasClass('ani')) {
$(this).removeClass("ani");
}
else {
$('.list').removeClass("ani");
$(this).addClass("ani");
}
});
you want to remove class ani on all the elements except the clicked one. You can use not()
$(".list").on('click', function(evt) {
$(".list").not($(evt.currentTarget)).removeClass("ani");
$(evt.currentTarget).toggleClass("ani");
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>

duplicating divs when reordering divs

Im trying to figure out the easiest way to re order some divs on a project im working on. I created this simple test: http://jsfiddle.net/Tt6uN/254/
$('.container > div').each(function() {
$(".green").insertBefore(".red");
});
div {
height: 100px;
width: 100px;
marign: 10px 0;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container">
<div class="red"></div>
<div class="green"></div>
<div class="green"></div>
</div>
As you can see there are 3 div elements in the code. Why is a fourth getting generated in the output? Also does anybody have a solution to my re ordering div problem. Regardless of where the red div is in the markup. it should always be after the green div

JQuery .attr tag not working

I don't understand why .attr() will not change the background-color of div "outline" to red.
HTML CODE:
<div id="outline"></div>
CSS CODE:
#outline {
height: 300px;
width: 300px;
background-color: black;
}
JAVASCRIPT (JQUERY) CODE:
$("#outline").attr('background-color', 'blue');
background-color isn't a html attribute, it's a style attribute - use css function instead.
$("#outline").css('background-color', 'blue');
#outline {
height: 300px;
width: 300px;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outline"></div>
// To set the html style attribute, use .css()
// .css() is dedicated to set one or more
// styles at a time
$("#outline").css('background-color','blue');
// This is equivalent to the above
// .attr() is dedicated to set one or more html
// attributes at a time
$("#outline").attr('style', 'background-color:blue');
#outline {
height: 300px;
width: 300px;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outline"></div>
background-color isn't an attribute, it's a css property.
Use :
$("#outline").css('backgroundColor', 'blue');

How to make more divs appear when hovering over one div?

I am trying to work out how to show more divs when hovering over one div.
I know how to show changes of the same div when hovering over it but how can I show more divs when hovering over one div?
Take this as an example:
http://jsfiddle.net/j4LFD/
How can I make it so when you hover over the box another box appears next to it?
Im not sure if this can be done with css or needs javascript?
Thanks!
James
You can do it with css like this:
.box , .appear{
background: #151515;
height: 100px;
width: 100px;
float:left;
}
.appear{
background:red;
display:none
}
.box:hover{
background: #e6e6e6;
height: 100px;
width: 100px;
}
.box:hover + .appear {
display:block;
}
Check this example http://jsfiddle.net/j4LFD/1/
To my knowledge it's not possible without Javascript, and I'd recommend using jQuery because it will make your life a lot easier. If you just want to show a div then you can do something similar to
<div id="div1">First Div</div>
<div id="div2" style="display:none">Second Div</div>
Then in the javascript
$('#div1').mouseover(function(){
$('#div2').show();
})
$('#div1').mouseout(function(){
$('#div2').hide();
})
If you actually want to add it dive on hover then you can use the jquery .append() function (http://api.jquery.com/append/)
Edit: Ok seeing sandeep's answer it clearly is possible in CSS, but still, this is how you'd do it in JS :-)
CSS solution: Use a parent/container div.
http://jsfiddle.net/samliew/j4LFD/4/
You can also do this with vanilla Javascript (no JQuery) and without having your elements be adjacent siblings. Example fiddle: http://jsfiddle.net/3nxfG/
html/js:
<div id="box1" class="box"></div>
<div id="box2" class="box hidden"></div>
<script type="text/javascript">
var box1 = document.getElementById('box1');
box1.onmouseover = function() {
var box2 = document.getElementById('box2');
box2.style.visibility = 'visible';
};
box1.onmouseout = function() {
var box2 = document.getElementById('box2');
box2.style.visibility = 'hidden';
};
</script>
css:
.box {
background: #151515;
height: 100px;
width: 100px;
float: left;
}
.hidden {
visibility: hidden;
}
You can fake it, use the box to hide the second box and the border to be the box,http://jsfiddle.net/j4LFD/3/

Categories

Resources