I'm building a carousel with basic jquery - I'm using the .css() rule to simply toggle opacity between each slide.
The way I want to do this is on click of each dot I want to check if the specific class exists and if it does hide all other items and show that one. So far I have:
$('.dot').click(function() {
$('.review-module--reviews').children().css('opacity', 0);
if ($('.dot').hasClass('dot1')) {
$('.review-one').css('opacity', 1);
$('.dot1').addClass('dot-active');
} else if ($('.dot').hasClass('dot2')) {
$('.review-two').css('opacity', 1);
$('.dot2').addClass('dot-active');
} else {
$('.review-three').css('opacity', 1);
$('.dot3').addClass('dot-active');
}
});
HTML:
<div class="review-module">
<div class="review-module--reviews">
<div class="review-one">
</div>
<div class="review-two">
</div>
<div class="review-three">
</div>
</div>
<span class="slider-dots">
<div class="dot dot1"></div>
<div class="dot dot2"></div>
<div class="dot dot3"></div>
</span>
</div>
However when I click on dots 2 and 3, it always targets the dot1 slide in the DOM. The 'dot-active' class gets added successfully to dot1 but on click of 2 and 3, that class does not get added.
I also tried explicity checking for a true value in the if statement like so:
if ($('.dot').hasClass('dot1') === true)
Is this the best way to do this? Or should I consider a different thought process?
The error is in this code:
if ($('.dot').hasClass('dotX'))
What you're actually doing here is fetching the list of all .dot elements and checking if the first one has the dotX class. As you can imagine, this will always pick up the first .dot element, which has the dot1 class.
What you probably mean to do is to check if the element that was clicked on has the dotX class, for which you need to check only that element.
Either do so by using the current scope of the click handler:
if ($(this).hasClass('dotX'))
or by checking the target of the click event:
$('.dot').click(function(e) {
$('.review-module--reviews').children().css('opacity', 0);
if ($(e.target).hasClass('dot1')) {
Try this may be it can help you -
JAVASCRIPT CODE-
$('.dot').click(function() {
$('.review-module--reviews').children().css('opacity', 0);
$('.dot').removeClass('dot-active');
if ($(this).hasClass('dot1')) {
$('.review-one').css('opacity', 1);
$(this).addClass('dot-active');
} else if ($(this).hasClass('dot2')) {
$('.review-two').css('opacity', 1);
$(this).addClass('dot-active');
} else {
$('.review-three').css('opacity', 1);
$(this).addClass('dot-active');
}
});
I suggest to use data-* attributes instead so give every .dot a data-review that refer to the related review div :
$('.review-module--reviews div').hide(); //Hide all the slides
$('.dot').click(function() {
var review = $(this).data('review');
$('.review-module--reviews div').hide(); //Hide all slides
$('.slider-dots .dot').removeClass('dot-active'); //Remove 'dot-active' class from all the dots
$(this).addClass('dot-active'); //Active the clicked dot
$('.review-'+review).show(); //Show the related slide
});
Then on click just get the review using jQuery method .data() and show the div with related class.
Hope this helps.
$('.review-module--reviews div').hide();
$('.dot').click(function() {
var review = $(this).data('review');
$('.review-module--reviews div').hide();
$('.slider-dots .dot').removeClass('dot-active');
$(this).addClass('dot-active');
$('.review-'+review).show();
});
.dot-active{
color: green;
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="slider-dots">
<div class="dot dot1" data-review="one">dot1</div>
<div class="dot dot2" data-review="two">dot2</div>
<div class="dot dot3" data-review="three">dot3</div>
</span>
<br>
<div class="review-module">
<div class="review-module--reviews">
<div class="review-one">
Review-one
</div>
<div class="review-two">
Review-two
</div>
<div class="review-three">
Review-three
</div>
</div>
</div>
Related
Sorry for the lack of knowledge but I don't know where else to turn. I had been working on the CSS for a project while the javascript was handled by a colleague. That colleague has now left the company and I have to finish his work to hit a deadline with very little knowledge of javascript. He had created a simple function (show/hide) that allowed us to show and hide content with an unordered list. Namely when you click on a list item, the corresponding div shows and the rest hides.
This was working fine, however I have since been asked to duplicate this so that multiple (show/hides) can be used on the page. When I did this the first one works ok, but the next scripts intefere with eachother and also hide content in the other divs. I've tried to fix this using my non-existent knowledge of javascript but to know avail (attempt is below). Any help here would be massively appreciated. Thanks in advance!
function toggle(target) {
var artz = document.getElementsByClassName('history');
var targ = document.getElementById(target);
var isVis = targ.style.display == 'block';
// hide all
for (var i = 0; i < artz.length; i++) {
artz[i].style.display = 'none';
}
// toggle current
targ.style.display = isVis? 'none' : 'block';
return false;
}
function toggle2(target) {
var artz2 = document.getElementsByClassName('vision');
var targ2 = document.getElementById(target2);
var isVis2 = targ.style.display == 'block';
// hide all
for (var i = 0; i < artz2.length; i++) {
artz2[i].style.display = 'none';
}
// toggle current
targ2.style.display = isVis2? 'none' : 'block';
return false;
}
jQuery(document).ready(function($) {
$('.slide-menu li a').on('click', function(){
$(this).parent().addClass('current').siblings().removeClass('current');
});
});
.container {
float: left;
}
.display-item {
display: none;
}
.display-item:first-of-type {
display: block;
}
.slide-menu li.current a {
color: #75aaaf;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="container">
<ul class="slide-menu" id="first">
<li class="current">1348</li>
<li>1558</li>
<li>1590</li>
</ul>
<div class="display-item history" id="1348" style="display:block;">History Content</div>
<div class="display-item history" id="1558">History Content2</div>
<div class="display-item history" id="1590">History Content3</div>
</div>
<div class="container">
<ul class="slide-menu" id="second">
<li class="current">Introduction</li>
<li>Highways</li>
<li>Transport</li>
</ul>
<div class="display-item vision" id="base" style="display:block;">Vision Content</div>
<div class="display-item vision" id="highways">Vision Content2</div>
<div class="display-item vision" id="transport">Vision Content3</div>
</div>
I think your code is okay if you intend duplicating the first toggle function in toggle2 function all you have to do is
Change the onclick event function from toggle to toggle2
<div class="container">
<ul class="slide-menu" id="second">
<li class="current"><a href="#/"
onclickk="toggle2('base');">Introduction</a></li>
<li><a href="#/"
onclick="toggle2('highways');">Highways</a></li>
<li><a href="#/"
onclick="toggle2('transport');">Transport</a></li>
</ul>
<div class="display-item vision" id="base"
style="display:block;">Vision Content</div>
<div class="display-item vision" id="highways">Vision
Content2</div>
<div class="display-item vision" id="transport">Vision
Content3</div>
</div>
This really isn't the way to set this up as it just causes the code to grow as more items need to be shown/hidden and the new code is largely the same as the old code. The original code also is more complex than it need be.
The following code will work no matter how many container structures you put on the page as long as you keep the structure the same as it is now. No ids are needed. No JQuery is needed either. You'll never need to touch the JavaScript, just add/remove HTML containers as you see fit.
See comments inline for details on what's happening.
.container {
float: left;
border:1px solid #e0e0e0;
margin:10px;
width:25%;
padding:3px;
}
/* Don't use hyperlinks <a></a> when you aren't
navigating anywhere. If you just need something
to click on, any element will do.
We'll just style the clickable elements to look like links
*/
.slide-menu > li {
text-decoration:underline;
cursor:pointer;
color: #75aaaf;
}
.hidden { display: none; } /* This class will be toggled upon clicks */
<!--
Don't use hyperlinks <a></a> when you aren't
navigating anywhere. If you just need something
to click on, any element will do.
The elements that should be hidden by default
will be so because of the "hidden" class that
they start off with.
No JQuery needed for this. Keep the HTML clean and
do all the event binding in JavaScript (no onclick="...")
-->
<div class="container">
<ul class="slide-menu">
<li class="current">1348</li>
<li>1558</li>
<li>1590</li>
</ul>
<div class="history" id="1348">History Content</div>
<div class="history hidden" id="1558">History Content2</div>
<div class="history hidden" id="1590">History Content3</div>
</div>
<div class="container">
<ul class="slide-menu">
<li class="current">Introduction</li>
<li>Highways</li>
<li>Transport</li>
</ul>
<div class="vision" id="base">Vision Content</div>
<div class="vision hidden" id="highways">Vision Content2</div>
<div class="vision hidden" id="transport">Vision Content3</div>
</div>
<!-- The following function will run automatically when this script element
is reached. Always keep the script just before the closing body tag (</body>). -->
<script>
(function(){
// Get any/all slide-menu elements into an array
let menus =Array.prototype.slice.call(document.querySelectorAll(".slide-menu"));
// Loop over the menus
menus.forEach(function(menu){
// Loop over the list items in the menu
Array.prototype.slice.call(menu.querySelectorAll("li")).forEach(function(item, index){
let idx = index;
// Set up a click event handler for each item
item.addEventListener("click", function(){
// Get all the <div> items in this menu into an Array
let divs = Array.prototype.slice.call(menu.parentElement.querySelectorAll("div"));
// Hide any item that was previously showing
divs.forEach(function(div){ div.classList.add("hidden"); });
// Query the parent element (the container) for all the
// corresponding <div> items and make it visible
divs[idx].classList.remove("hidden");
});
});
});
}());
</script>
I'm faily new to jquery and coding in general. I'm having a few troubles with this.
What i want is for when the page loads, the 'Vlogging' link is active and 'Details 1' is shown. Then when you click on either 'Filmmaking' or 'Beme'... 'Details 2 or 3 is shown and which ever one was there goes away.
I have everything set up right so far just need to get it to where when you click on one of the other links the correct 'Details' text shows itself.
Thank you so much and i have it in a fiddle right now!
http://jsfiddle.net/t1huc43d/
Here is the code than needs tuned:
$(function() {
$("togglediv1").click(function() {
$("#togglediv1").removeClass("display-start");
$("li").removeClass("display");
$(this).addClass("display");
});
});
This code will save you a lot of time. I added a custom attribute called "data". This attribute is used to tie the link to the tab you wish to display. This code will make it a lot easier to add additional tabs and etc. Look at the bottom for the changed HTML and JavaScript.
<div id="wrap">
<ul id="divtoggle">
<li><a class="link" data="1">Vlogging</a></li>
<li><a class="link" data="2"> Filmmaking</a></li>
<li><a class="link" data="3"> Beme</a></li>
</ul>
<div class="text">
<div class="tab" data="1">Details 1</div>
<div class="tab" data="2">Details 2</div>
<div class="tab" data="3">Details 3</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function () {
$(".link").click(function () {
$(".active").removeClass("active");
$(this).addClass("active");
dataAttr = $(this).attr("data");
$(".tab").hide();
$(".tab[data="+dataAttr+"]").show();
});
$(".link:first").click();
});
</script>
$(function() {
$("#togglediv1").click(function() {
$("#one").removeClass("display");
$("#one").addClass("display-start");
$("#two").removeClass("display-start");
$("#two").addClass("display");
$("#three").removeClass("display-start");
$("#three").addClass("display");
});
});
$(function() {
$("#togglediv2").click(function() {
$("#one").removeClass("display-start");
$("#one").addClass("display");
$("#two").removeClass("display");
$("#two").addClass("display-start");
$("#three").addClass("display");
$("#three").removeClass("display-start");
});
});
...
Updated jsfiddle: http://jsfiddle.net/t1huc43d/3/
Since your ids aren't that conducive in tracking what is clicked and what isn't, I decided to just use this to find what you've clicked in correspondence with the details.
Your updated javascript:
$(function() {
$("li").click(function() {
$("#togglediv1").removeClass("active-start");
$("li").removeClass("active");
$(this).addClass("active");
let temp = $("#divtoggle").children();
var index;
for (let i = 0; i < temp.length; i++)
{
if (this == temp[i] )
{
index = i;
break;
}
}
$(".display-start").addClass("display");
$(".display-start").removeClass("display-start");
let text_children = $(".text").children()
let the_child = text_children[index];
$(text_children[index]).addClass("display-start");
$(text_children[index]).removeClass("display");
});
});
JQuery actually has some components to help you out, but to me, the shortest and CLEANEST way of doing this is the following:
The first thing I'd do is set an id of each of the titles, incrementing them by 1. Then, I'd do the same for the details like so:
<div id="wrap">
<ul id="divtoggle">
<li><a class="title" id="title-1">Vlogging</a></li>
<li><a class="title" id="title-2"> Filmmaking</a></li>
<li><a class="title" id="title-3"> Beme</a></li>
</ul>
<div class="text">
<div class='display' id="detail-1">Details 1</div>
<div class='display' id="detail-2">Details 2</div>
<div class='display' id="detail-3">Details 3</div>
</div>
</div>
After that, the JQuery is pretty simple. Setup a click event on the class title. The first thing to do is to parse the id of the clicked title. Once you have that, target the related detail and show it:
$(document).ready(function() {
$(".title").click(function() {
//*** get id
var id = $(this).attr("id").split("-")[1];
if (typeof id != "undefined"){
//*** hide other descriptions and show yours
$(".display").hide();
$("#detail-" + id).show();
}
});
});
DEMO: http://jsbin.com/volikofihe/edit?html,js,console,output
Here you go. Simplified your CSS a little. Toggling a .active class on the top links, and a .display class on the text divs. When you click on a link, the code uses the $.index() of that link in the list as the index of the text div to show. So if you click on the 2nd link, it will show the 2nd text box.
$(function() {
$toggleLinks = $('#divtoggle a'),
$displays = $('.text div');
$toggleLinks.on('click', function(e) {
e.preventDefault();
$toggleLinks.removeClass('active');
$(this).addClass('active');
$displays.removeClass('display');
$displays.eq($(this).closest('li').index()).addClass('display');
});
});
li {
color: grey;
font: effra;
font-weight: bold;
}
a:hover {
color: #aaaaaa;
cursor: pointer;
}
.active {
color: orange;
}
.text div {
display: none;
}
.text .display {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<ul id="divtoggle">
<li><a class="active">Vlogging</a></li>
<li><a>Filmmaking</a></li>
<li><a>Beme</a></li>
</ul>
<div class="text">
<div class='display'>Details 1</div>
<div>Details 2</div>
<div>Details 3</div>
</div>
</div>
Preserved as much of your existing code as possible. Updated fiddle.
I added a data-controls custom attribute to each of your li elements so as to associate them to each of the corresponding data divs:
<li data-controls="one"><a id="togglediv1" class="active-start">Vlogging</a></li>
<li data-controls="two"><a id="togglediv2"> Filmmaking</a></li>
<li data-controls="three"><a id="togglediv3"> Beme</a></li>
Then I updated the JavaScript to remove and add the classes, as needed.
I am facing an issue about this.
<div id="1">
<div id="2">
</div>
<div id="3">
<div id="4">
</div>
</div>
</div>
<div id="others_div">
</div>
I want to add the class "hidden" to "1" when I click on something which is not "1" nor one of its children.
Now I am using this but I have a lack of imagination for solving this issue...
document.onclick = function(e)
{
if(e.target.id!="1")
{
$("#1").addClass("hidden");
}
}
Well, to avoid e.stopPropagation() (maybe you want that event to bubble up to some other ancestor) You can check if it is not clicked on #1 nor on it's children like this:
$('body').on('click', function(e) {
if (!((e.target.id== "1") || $(e.target).closest('#1').length)) {
$("#1").addClass("hidden");
}
});
You could use a jQuery check like the following one to check if the current element is your 1 element or traverse the DOM to see if the current target is contained within an element with an ID of 1 :
<script>
$(function(){
// Trigger this when something is clicked
$(document).click(function(e){
// Toggle the hidden class based on if the current element is 1
// or if it is contained in an element with ID of 1
$("#1").toggleClass('hidden',!((e.target.id== "1") || $(e.target).closest('#1').length))
});
});
</script>
Generally, you should avoid using ID attributes that only consists of numbers as they are not valid (ID attributes must begin with a letter). Ignoring this could result in some issues with regards to CSS or jQuery selection.
JQuery
$('body').on( "click", function(e) {
if(e.target.id !== "1")
{
$("#1").addClass("hidden");
}
});
I think you want this
// taken from http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element
$('html').click(function() {
//Hide the menus if visible
alert('hide');
});
$('#one').click(function(event){
event.stopPropagation();
});
div#one {
background: yellow;
}
div#others_div {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="one">
div one
<div id="2">
div two
</div>
<div id="3">
div three
<div id="4">
div four
</div>
</div>
</div>
<div id="others_div">
other div
</div>
So I'm using classes to sort different content, but I'm not actually sure how to apply this sorting.
<div class="class1"><div class="heads">Title</div>
<div class="description"><p>Class 1 Item 1</p></div></div>
<div class="class2"><div class="heads">Title</div>
<div class="description"><p>Class 2 Item 1</p></div></div>
<div class="class2"><div class="heads">Title</div>
<div class="description"><p>Class 2 Item 2</p></div></div>
<div class="class3"><div class="heads">Title</div>
<div class="description"><p>Class 3 Item 1</p></div></div>
So let's say the user clicks a button that says 'Class 2'. I want the opacity of everything that is not class 2 to be, say, .5 while class 2's opacity stays at 1. I've tried using .not(), but I'm not familiar with it and most examples use it in conjunction with .siblings(), and I don't want the siblings to fade either. Help? I'm not sure what to do.
Edit: Sorry about the orphan s. ^_^; Fixed them!
http://jsfiddle.net/orjj65g0/7/
$("#container button").click(function() {
var className = $(this)[0].className;
$("#container button").each(function() {
if($(this)[0].className !== className) {
$(this).next().addClass("op05");
$(this).next().removeClass("op1");
} else {
$(this).next().addClass("op15");
$(this).next().removeClass("op05");
}
});
});
With $("#container button").click(...) you access every button in #container.
$(this).[0].className is the class name of the button you have clicked.
After you have clicked the button, you go through every button in the container:
$("#container button").each(...)
In the container you compare the class names with the clicked class name. If there are not the same, than add the class "op05" to the div after the button and remove the class "op1" from the div after the button:
(Example:
<button class="classN">click</button>
<div class="content">div after button</div>
$(".classN").next()...
)
Here:
$(this).next()...
And with all the div's after the button(s), that have the same class name happens the same with the 'opposite' class names.
$("div").not(".class2").css("opacity", "0.5")
will set opacity of all divs except for ones with class class2 to 0.5.
If you are using a container:
$('.container>div:not(.class2)').css('opacity', 0.5);
1. You have invalid HTML. a tag opening is missing. Based on my assumptions, that's how it should look like:
<div class="classX">
Title
</div>
<div class="description">
<p>Class X Item 1</p>
</div>
But it's very unintuitive syntax. What is .description content for? I suggest you to rewrite syntax. For example:
<div class="classX">
Title
<div class="description">
<p>Class X Item 1</p>
</div>
</div>
2. You can use .not() method or :not() selector in jQuery
According to my version of HTML. Let's code!
$("a").on('click', function(){
var $t = $(this).parent(); // clicked div.class2 for example
$t.css("opacity", 1).siblings().css("opacity", 1); // undo selection
$t.siblings().not("."+$t.attr("class")).css("opacity", 0.5);
// hide other classes. Equivalent with selector:
//$t.siblings(":not(."+$t.attr("class")+")").css("opacity", 0.5);
});
Check it that's what you want: http://jsfiddle.net/Tymek/2k85m8r9/
I am trying to style div and ul to function like . However, I have a problem that:
1) I only want to toggle the ul that I click and hide the other ul. So I wonder if jquery support some function such as 'not click'?
2) I want to hide all the ul when the mouse is click outside. I did some research, and see other people use mouseup or click on body. But I am not quiet sure how it works.
$(document).ready(function() {
$('.hide').each(function() {
$(this).hide();
});
$('.select').click(function() {
var id = '#' + $(this).attr('id');
var sub = id + '_sub';
$(sub).slideToggle();
});
$('body').mouseup(function() {
if($(this).length == 0) {
$(this).hide();
}
});
});
div.select {
display: inline-block;
margin: 10px;
padding: 20px;
background: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="1" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="1_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
<div id="2" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="2_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
<div id="3" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="3_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
</body>
here you go: DEMO
$(document).ready(function() {
$('.hide').hide(); //hide in the beginning
$('.select').click(function() {
$('.hide').slideUp(200); //hide all the divs
$(this).find('.hide').slideDown(200); //show the one that is clicked
});
$(document).click(function(e){
if(!$('.select').is(e.target) || !$('.select').has(e.target)){ // check if the click is inside a div or outside
$('.hide').slideUp(200); // if it is outside then hide all of them
}
});
});
you can define your notClick() function as below:
$.fn.notClicked= function(clickPosition){
if (!$(this).is(clickPosition.target) && $(this).has(clickPosition.target).length === 0){
return true;
}
else{
return false;
}
};
and then use it as:
$(document).click(function(e){
alert($('.select').notClick(e)); // will return true if it is not clicked, and false if clicked
});
You need to hide other ul whenever some one clicks on .select div.
Here is a working fiddle: http://jsfiddle.net/0mgbsa0b/1/
$(document).ready(function() {
$('.hide').each(function() {
$(this).hide();
});
$('.select').click(function() {
$('.hide').each(function() {
$(this).hide();
});
var id = '#' + $(this).attr('id');
var sub = id + '_sub';
$(sub).slideToggle();
});
$('body').mouseup(function() {
if($(this).length == 0) {
$(this).hide();
}
});
});
I'm interested in two concerns you raised, so i will be trying to share some ideas on them:
1)So I wonder if jquery support some function such as 'not click'?
personally, to quesiton1
i think there is no jQuery event method called .noclick()
PPL often use addClass & removeClass to log whether an element got clicked and after marking the element with class="active" , using jQuery selector to select ".active" or using jQuery ":not" selector to select elements that are not marked ".active" ( indirectly finding out those unclicked.)
3.You might also need to count in click propagation issues. meaning sometimes you click a children container and triggered click event towards all its parent inside.
fiddle link: `http://jsfiddle.net/hahatey/ctp5jngf/2/`
In the above case , if you clicked child box in red, will by default alert1, alert2 if
you didn't apply a e.stopPropagation() to the click event;
2) I want to hide all the ul when the mouse is click outside. I did some research, and see other people use mouseup or click on body. But I am not quiet sure how it works.
for question 2:
could be many many ways to do it, you can try blur() //lose focus event trigger.
like what you mentioned mouseout, mouseup, add click event listener to outer area all will work for it as long as u can use method in answer1. i see other ppl have posted many answers already as it can be done in many ways.