JQuery hide multiple div of similar id when clicked outside - javascript

I want to hide all the div with similar id if not clicked on any of those div's. In my code it is working only for the first div since I have use index[0] to fetch the id. I want to generalize it to work for all the id.
Here is the code:
$(window).click(function(e) {
if (e.target.id != $('[id^=div_]')[0].id) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>
FIDDLE

The simple solution here is to use a common class on all the elements. You can then use is() to determine if e.target was one of those elements and hide/show them as needed. Try this:
$(window).click(function(e) {
if (!$(e.target).is('.div')) {
$('.div').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
I cannot make any changes in HTML like adding classes
In that case you can check the id of the clicked element to see if it begins with div_. If not, then hide all the divs, something like this:
$(window).click(function(e) {
if (e.target.id.indexOf('div_') != 0) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>

Hey you can use this function
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
filter function will filter the selected div in list of div whoes id starts with div
$(window).click(function(e) {
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>

Related

How can I remove class when click the same button

Please see code below:
const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
sectionBtn.addEventListener("click", (btns)=> {
// console.log(sectionIconHover)
const containerTarget = btns.currentTarget.parentElement.children[1]
const containerHoverTarget = btns.currentTarget.parentElement.children[0]
sectionContainer.forEach(items => {
if(items !== containerTarget) {
items.classList.remove("show")
// itemHover.classList.remove("rb")
}
})
sectionIconHover.forEach(itemHover => {
if(itemHover !== containerHoverTarget) {
itemHover.classList.remove("rb")
}
})
containerTarget.classList.toggle("show")
containerHoverTarget.classList.add("rb")
})
})
.nk-section-icons {
height: 30px;
min-width: 30px;
width: 30px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 3px;
background: yellow;
margin-bottom: 5px;
}
.nk-section-icons.rb {
background: black;
}
.nk-sec-container {
width: 300px;
min-width: 300px;
height: 100%;
background: red;
position: absolute;
z-index: 11;
box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
border-radius: 6px;
left: 70px;
top: 0px;
}
.nk-sec-container.show {
background: green;
}
.nk-section-icons-container {
position: relative;
}
<div class="nk-section-l-icons">
<div class="nk-section-icons-container">
<div class="nk-section-icons fav" data-title="Favorites">btn</div>
<div class="nk-sec-container nk-sec-fav-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons recent" data-title="Recent">btn</div>
<div class="nk-sec-container nk-sec-recent-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons notifs" data-title="Notifications">btn</div>
<div class="nk-sec-container nk-sec-notif-c">
</div>
</div>
</div>
Hello guys, can you please see my code? Currently, it's working fine when I click the button it's working the classes are moved when I click any of the buttons. However, if I tried clicking the same button again the class rb is not removed but the show class is removed. Can you please help me with how can I fix this? Thanks
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if($("p").hasClass("main"))
{
$("p").toggleClass("main1");
}
else
{
$("p").toggleClass("main");
}
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
.main1 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>
</body>
</html>
Use toggling: Toggle between adding and removing the "main" class name for all elements
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

Apply click method to outer div but not inner div [duplicate]

This question already has answers here:
How do I prevent a parent's onclick event from firing when a child anchor is clicked?
(25 answers)
Closed 5 years ago.
In this example I want the alert to be triggered when the black outer div is clicked but not when anything inside the inner div is clicked.
Currently when I click the inner button it triggers the alert.
$("#outer").click(function() {
alert("triggered");
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
I want inside the inner div nothing to trigger the alert. How do i do this?
(for some reason inner button isn't showing in snippet, here is codepen link: https://codepen.io/GuerrillaCoder/pen/Pmvmqx)
You just need to check for id of element, as inner is child element, it will always propagate the event to parent element (outer).
$("#outer").click(function(event) {
if(event.target.id=="outer"){
alert("triggered");
}
});
You can use event.stopPropagation(); when clicking the inner div:
$("#outer").click(function() {
alert("triggered");
});
$('#inner').click(function (evt) {
evt.stopPropagation();
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
In the click function check event target equal to outer
$("#outer").click(function(e) {
if (e.target.id === "outer"){
alert("triggered");
}
});
I think event.stopPropagation() method would be most useful solution.you only need to call it on the children of outer div:
$("#outer").on('click', function () {
alert("triggered");
}).children().on('click', function (e) {
e.stopPropagation();
});
Also check this Solution.
Pure javascript solution, if anyone cares -))
var inner = document.getElementById("inner");
var btn = inner.querySelector("button");
document.getElementById("outer").addEventListener("click", function(e) {
(e.target == btn) || (e.target == inner) ? console.log("click triggered from"+ e.target+". so we do not alert anything") : alert("something");
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
Another way to do this:
$("#outer").click(function() {
alert("triggered");
});
$("#inner").click(function(e) {
e.stopPropagation()
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
You can use event.target to check event if is triggered by parent or by its children:
$("#outer").click(function(e) {
if( e.target !== this ) {
return;
} else {
alert("triggered");
}
});
Try this
$("#outer").click(function(e) {
e.target.id=='outer'?alert('triggered'):void(0);
});

Looking for ways to refactor my jQuery code for a div toggle I created

I wrote some code with three things in mind:
Highlighting a selection's border using 'on click'.
Selecting one item will remove the highlight from the other item.
The ability to deselect each item on click.
I've managed to get everything working for the most part, but I don't particularly like how complex the code is for the radial dot that appears when one item is selected.
Below is an example of what I'm talking about, particularly I'm looking for ways to refactor the code below into something a little more legible (shorter).
$(this).children('.radial').children().toggleClass('checked').parents('.itembox')
.siblings().children('.radial').children().removeClass('checked');
Here's a working example for more context (line 10):
var raceInternet = false;
var racePhone = false;
var raceTv = false;
$(function() {
var $targetDiv = $('#race-internet > .itembox');
var $radialDot = $('.radial > .center-dot');
$targetDiv.on('click', function() {
$(this).toggleClass('user-selected').siblings().removeClass('user-selected');
//Is it possible to refactor Line 10?
$(this).children('.radial').children().toggleClass('checked').parents('.itembox').siblings().children('.radial').children().removeClass('checked');
if ($targetDiv.is('.user-selected')) {
raceInternet = true;
} else {
raceInternet = false;
}
})
})
.itembox-container {
display: flex;
}
.boxes-2 {
width: calc((100% - 25px)/2);
margin: 10px;
padding: 10px;
}
.itembox {
position: relative;
display: inline-block;
border: 5px solid #e8e8e8;
border-radius: 10px;
cursor: pointer;
}
.user-selected {
border: 5px solid #E16E5B;
}
.itembox h4 {
color: #22ddc0;
font-weight: 700;
}
span.price {
display: inline-block;
font-weight: 400;
float: right;
color: #22ddc0;
}
.itembox > ul {
list-style: none;
}
.itembox > ul > li {
line-height: 3;
}
.radial {
position: absolute;
float: right;
height: 35px;
width: 35px;
padding: 2px;
border: 5px solid #e8e8e8;
border-radius: 50%;
top: 43%;
right: 10px;
}
.center-dot {
display: none;
position: relative;
height: 21px;
width: 21px;
background-color: #E16E5B;
border-radius: 50%;
}
.checked {
display: block;
}
.prime-aux:first-of-type {
top: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
<!-- Primary Content Container -->
<div class="prime-aux">
<div id="race-internet" class="itembox-container">
<div class="itembox boxes-2">
<h4>Gigabit Internet <span class="price">$60/mo</span></h4>
<ul>
<li>1,000 Mbps</li>
<li>No data caps</li>
</ul>
<div class="radial">
<div class="center-dot"></div>
</div>
</div>
<div class="itembox boxes-2">
<h4>Basic Internet <span class="price">$25/mo</span></h4>
<ul>
<li>25 Mbps</li>
<li>No data caps</li>
</ul>
<div class="radial">
<div class="center-dot"></div>
</div>
</div>
</div>
</div>
</section>
<!-- Primary Content Container End -->
View on JS Fiddle
You can eliminate a lot of your jQuery by just leveraging CSS. Typically, if I want to toggle a feature, I have it either display: block; or display: none; based upon a CSS selector. Then, I just use jQuery to toggle the parent element's class name. So for example:
.item.selected .checkmark {
display: block;
}
.item .checkmark {
display: none;
}
$('.item').click(function(){ $(this).toggleClass('selected') });
JSFiddle

Swapping an image when a toggle has been clicked on

I have the following code where I added a plus symbol to one of my service titles. I was informed by someone that when that service is clicked on I should have a minus sign take its place to show that it can be minimized. I am unsure of how to swap out the plus sign when the description has been expanded. Does anyone have any ideas of how I could do that?
Here is a snippet. Click on one of the service names to see the description expand.
$('.service_wrapper').click(function() {
var thisDescription = $('.service_description', $(this));
// Hide all other descriptions
$('.service_description').not(thisDescription).hide();
// Toggle (show or hide) this description
thisDescription.slideToggle(500);
});
.service_wrapper {
border: 1px solid black;
margin: 15px;
width: 20%;
}
.service_list {
margin-left: 20%;
}
.service_title {
padding: 15px 12px;
margin: 0;
font-weight: bold;
font-size: 1em;
}
.service_title:hover {
background-color: gray;
color: blue;
cursor: pointer;
}
.service_description {
display: none;
padding: 8px 14px;
width: 100%;
margin-top: 10px;
font-size: .9em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service_list">
<div class="service_wrapper">
<div class="service_title">
<img src="http://realtorcatch.com/icons/plusSymbol.png" alt="Service" style="width:10px;height:10px;">Floors</div>
<div class="service_description">The best floors!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Roofs</div>
<div class="service_description">Your roof will be perfect!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Siding</div>
<div class="service_description">mmmm siding.</div>
</div>
<div class="service_wrapper">
<div class="service_title">Paint</div>
<div class="service_description">Fabulous paint!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Kitchen Remodels</div>
<div class="service_description">Pretty kitchen.</div>
</div>
</div>
Here is the working example, i change a little de html and Js
$('.service_wrapper').click(function() {
var thisDescription = $('.service_description', $(this));
var t = $(this);
if(t.hasClass('open'))
{
t.removeClass('open');
t.find('.status').html("+");
}else {
t.addClass('open');
t.find('.status').html("-");
}
// Hide all other descriptions
$('.service_description').not(thisDescription).hide();
// Toggle (show or hide) this description
thisDescription.slideToggle(500);
});
the working example
I'd suggest simply toggling a class to achieve this.
You can add the icon as a background image of a pseudo element inserted into the .service_title element. Then you can simply toggle a class in order to change the icon. Update the background image URLs accordingly. See the updated example for the modified jQuery; it's still only 5 lines.
The relevant CSS:
.service_title:before {
content: '';
background: url('http://i.stack.imgur.com/GC7i2.png') 0 0 / 10px 10px no-repeat;
width: 10px;
height: 10px;
display: inline-block;
vertical-align: middle;
}
.closed .service_title:before {
background-image: url('http://i.stack.imgur.com/ma4L4.png');
}
Updated Example:
$('.service_wrapper').click(function() {
var thisDescription = $('.service_description', $(this));
$('.service_description').not(thisDescription).hide().parent().removeClass('closed');
thisDescription.slideToggle(500).parent().toggleClass('closed');
});
.service_wrapper {
border: 1px solid black;
margin: 15px;
width: 20%;
}
.service_list {
margin-left: 20%;
}
.service_title {
padding: 15px 12px;
margin: 0;
font-weight: bold;
font-size: 1em;
}
.service_title:before {
content: '';
background: url('http://i.stack.imgur.com/GC7i2.png') 0 0 / 10px 10px no-repeat;
width: 10px;
height: 10px;
display: inline-block;
vertical-align: middle;
}
.closed .service_title:before {
background-image: url('http://i.stack.imgur.com/ma4L4.png');
}
.service_title:hover {
background-color: gray;
color: blue;
cursor: pointer;
}
.service_description {
display: none;
padding: 8px 14px;
width: 100%;
margin-top: 10px;
font-size: .9em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service_list">
<div class="service_wrapper">
<div class="service_title">Floors</div>
<div class="service_description">The best floors!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Roofs</div>
<div class="service_description">Your roof will be perfect!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Siding</div>
<div class="service_description">mmmm siding.</div>
</div>
<div class="service_wrapper">
<div class="service_title">Paint</div>
<div class="service_description">Fabulous paint!</div>
</div>
<div class="service_wrapper">
<div class="service_title">Kitchen Remodels</div>
<div class="service_description">Pretty kitchen.</div>
</div>
</div>
You could just change it within your click binding...
Let's say your using images, just add a data-attribute you can query when you need to, like this...
HTML
<div class="service_wrapper">
<img data-state="plus" class="state" src="plus.png" alt="More"/>
<div class="service_title">Paint</div>
<div class="service_description">Fabulous paint!</div>
</div>
JS
$('.service_wrapper').click(function() {
var state = $(this).find('.state');
if(state.data('state') == 'plus')
state.attr({ 'src': 'minus.png', 'alt': 'Less' }).data('state', 'minus');
else
state.attr({ 'src': 'plus.png', 'alt': 'More' }).data('state', 'plus');
});

How to center all list's elements to parent div

I am going to add dynamically elements to my block of ul.
I would like to center all list's elements to parent div(brown boder).
For example,
if the resolution of the browser allows you to set two blocks in one row, I would like to center this row in relation to parent div.
I would be very graftefully.
Link to demo
myCode:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
var tab = [2,3,4,5,7,8,9,11,12,13,14,15];
$(document).ready(function(){
$('#godziny').on('click', '.godzina', function(){
//alert(this.attr('class'));
$('.yb').removeClass('yb');
$(this).addClass('yb');
});
$('#getElements').click(function() {
for(i = 0; i < tab.length; ++i) {
alert(tab[i]);
setTimeout(function(i){
$('#godziny').append('<li class="godzina">' + tab[i] + '</li>');
}, i*50);
}
});
});
</script>
<style>
#spisSalonow {
margin: 0 auto;
}
#spisSalonow > div {
padding-top: 15px;
color:red;
}
#wybor_terminu {
border: 1px solid brown;
}
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
border: 1px solid red;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
float: left;
cursor: pointer;
margin-right: 40px;
margin-top: 40px;
/*margin:auto;*/
/*
opacity: 0.4;
filter: alpha(opacity=40);
*/
}
.yb {
background: yellow;
}
</style>
</head>
<body>
<div id="wrapper">
<input type="button" value="get Elements" id="getElements"/>
<section id="content">
<div class="full">
<BR/>
<div id="wybor_terminu" class="center border" style="width: 70%; position: relative;">
<div style="text-align: center"><img src="https://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-05-24.png" alt="Left Arrow" /> <span id="day"> ANY DAY </span> <img src="http://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-06-24.png" alt="Right Arrow" /></div>
<ul id="godziny" style="margin-top: 25px;">
</ul>
</div>
</section>
</div>
</body>
</html>
You can use the CSS flexbox to achieve this. Here is a link to a complete guide on how to use flexbox. I hope this helps.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Add this lines:
CSS
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
/*NEW*/
padding: 0;
width: 100%;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
/*float: left; You don't need this line*/
cursor: pointer;
/*NEW*/
margin:auto;
margin-top: 40px;
}
EDIT
This is only a quick solution with bootstrap maybe it could help you a little bit. jsfiddle
jQuery
In this line I added bootstrap classes:
$('#godziny').append('<li class="godzina col-sm-12 col-md-6">' + tab[i] + '</li>');
This code center your boxes (is not the best solution, but it works):
countBoxes = $('#godziny').width() / 200;
alignBoxes = ($('#godziny').width()-(200*parseInt(countBoxes)))/2;
if(countBoxes >= 2.65){
$('#godziny').css('margin-left', alignBoxes);
} else{
$('#godziny').css('margin-left', 0);
}
If you change the resolution of your screen, click the button to center your boxes again.

Categories