I have a parent <div>, #amwcontentwrapper, which has a series of divs within it with their own classes and ids.
I want to use jQuery to select these child divs, and IF they have the class .amwhidden, do nothing, but if not, remove the .amwshown class and add the .amwhidden class.
This is what I have so far, but it is not working. I think it may be my selecting of the child divs within the parent.
Can anybody see any obvious problems? Thanks for your help.
if ($('#amwcontentwrapper > div').hasClass('amwhidden')){
} else {
$('#amwcontentwrapper > div').fadeIn(600, function(){
$('#amwcontentwrapper > div').removeClass('amwshown');
$('#amwcontentwrapper > div').addClass('amwhidden');
});
}
And here is the basic html that I am using:
<div class="amwshown" id="amwintro">
Intro Section, which should have the 'amwshown' class removed, and the
'amwhidden' class added, when the jQuery runs. Currently, this does not happen.
</div>
UPDATE: Using War10ck's solution in the comments below (i.e. $('#amwcontentwrapper > div.amwshown')) I have managed to get the classes changing as I wished. However, those which have had the .amwshown class removed and .amwhidden class added still show on the page, despite the CSS looking like this:
.amwhidden {
display:none;
}
.amwshown {
display:block;
}
Looking at the Dev Tools, it seems that, when the jQuery is run (on a click event) the classes are changing, but any classes which are having the .amwshown class added (thus displaying them on the page) are also having the a <style> tag added to them which makes them display:block;
When I then press another button, which should hide the aformentioned <div> to make way for another one, the class is being changed to .amwhidden, but that <style> tag is not being deleted, so even though it has the .amwhidden class, it is still on the page.
I've created a JSFiddle here, if anybody still wants to help!
`
$(document).ready(function() {
$('#buybutton').click(function() {
$('#amwcontentwrapper > div.amwshown').fadeIn(600, function() {
$(this).removeClass('amwshown').addClass('amwhidden');
});
if ($('#amwbuy').hasClass('amwshown')) {} else {
$('#amwbuy').fadeIn(600, function() {
$('#amwbuy').removeClass('amwhidden');
$('#amwbuy').addClass('amwshown');
});
}
});
$('#phdbutton').click(function() {
$('#amwcontentwrapper > div.amwshown').fadeIn(600, function() {
$(this).removeClass('amwshown').addClass('amwhidden');
});
if ($('#amwphd').hasClass('amwshown')) {} else {
$('#amwphd').fadeIn(600, function() {
$('#amwphd').removeClass('amwhidden');
$('#amwphd').addClass('amwshown');
});
}
});
});
#sidebar {
position: absolute;
left: 1%;
top: 1%;
font-size: 5em;
color: #000000;
width: 10%;
display: block;
background-color: red;
}
#amwcontentwrapper {
position: absolute;
left: 20%;
top: 5%;
}
.amwshown {
display: block;
}
.amwhidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="amwsidebar">
<span class="sidebarbutton" id="phdbutton">PhD Button</span>
<br />
<br />
<span class="sidebarbutton" id="buybutton">Buy Button</span>
</div>
<div id="amwcontentwrapper">
<div class="amwshown" id="amwintro">
<p>An intro section to welcome the visitor. Disappears when one of the other sections is clicked.</p>
<br />
<br />
</div>
<div class="amwhidden" id="amwbuy">
Buy Section
</div>
<div class="amwhidden" id="amwphd">
PhD Section
</div>
</div>
`
You can use not to remove the elements you do not want, like this:
$('#amwcontentwrapper > div').not('.amwhidden')
.removeClass('amwshown')
.addClass('amwhidden');
And work with that.
Try this
$(document).ready(function() {
$("#amwcontentwrapper").children().each(function(elem, x) {
if ($(x).attr("class") == "amwhidden") {
alert($(x).attr("class"));
$(x).removeClass("amwhidden").addClass("amwshow");
alert($(x).attr("class"));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="amwcontentwrapper">
<div class="amwhidden"></div>
<div></div>
<div></div>
</div>
You can try each as follow,
$("#amwcontentwrapper div").each(function(){
if($(this).hasClass('amwhidden'))
//DO something
else
//DO something
});
Thank you for all help, it has prompted some brainstorming which has solved this issue.
Instead of adding the .amwhidden class and removing the .amwhidden class using jQuery, I have just created a .amwsection class, which all the sections belong to which has an initial display value of none. So far, so good; all of the sections are not there when you load up the page.
Then I use the .css jQuery function to change the display:none to display:block when the corresponding button is clicked, and changing all other .amwsections to display:none. This works just fine, but the effect is quite abrupt; there is no fading in, as you would get if you used the .animate function. .animate, however, does not work with the display value.
.fadeOut and .fadeIn to the rescue! By wrapping the .css change in these, I can create a fading in/out effect and can still use the display value.
Here is one example of this code.
The #buybutton is the button to be pressed.
#amwintro is just something which appears when the page loads - it will now be set to display:none if this is the first button pressed.
The .amwsection are all of the hidden sections. This portion of the code just resets all of them. This and the #amwintro section happen very quickly (1/100th of a second) to keep response time good.
The #amwbuy is the specific section that I want to reveal. As you can see, this fades in over a longer period.
Currently only tested in Chrome, but I think I've got it!
$(document).ready(function () {
$('#buybutton').click(function() {
$('#amwintro').fadeOut(1, function() {
$(this).css({
display:'none',
});
});
$('.amwsection').fadeOut(1, function() {
$(this).css({
display:'none',
});
});
$('#amwbuy').fadeIn(600, function() {
$(this).css({
display:'block',
});
});
});
});
Related
Ok so I have a div that contains a canvas and a span which contains an image. I want it such that if the user hovers over or focuses on the div that the image inside of the span will appear. The image wil be invisible otherwise.
Long story short I want to have a canvas with a red 'X' on the corner that is only visible when the canvas is active
$('image-canvas').hover(function() {
$('delete-image').addClass('active');
}, function() {
$('delete-image').removeClass('active');
})
.delete-image {
position: absolute;
top: 0px;
right: 0px;
}
.delete-image>img {
width: 32px;
visibility: hidden;
}
.delete-image.active>img {
width: 32px;
visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canvas-container" tabindex="1">
<canvas id="imageCanvas"></canvas>
<span class="delete-image">
<img src="file:///E:/Apps/Emoji-App/emojis/icons/if_erase_delete_remove_wipe_out_181387.png"/>
</span>
</div>
The hover event fires just fine but the image refuses to toggle visibility. Any help?
When you use a class within your selector, write it like this:
$('.myDiv')
When you use an ID within your selector, write it like this:
$('#myDiv')
For further informations, check out jQuery's learning center website.
Seems like you have misspelled or have not specified the jQuery selector type (class . or id #). Please try this:
$('#imageCanvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
See here .
$("#control").mouseover(function(){
$('#img').show();
});
$("#control").mouseout(function(){
$('#img').hide();
});
#img{
display:none;
}
#control{
margin-bottom:10px;
padding:5px;
background-color:#eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='control'>Show/Hide</div>
<img src='https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg' id='img'>
The question is not well-phrased, so I ain't sure I totally understood what you wanted.
When you try to select by class, don't forget the dot '.'
$('image-canvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
When using functions 'addClass', 'removeClass', 'toggleClass', etc. - you don't use the '.' sign because it is a function that refers only to classes. On the other hand, when using jQuery selector $(' ') or vanilla querySelector(' '), you should declare what kind of attribute you are selecting by, those will be '#' for ID, '.' for Class, and if you want to select by anything else you can use $('*[anyattribute=anyvalue]'), in your clase it could be $('span[class=delete-image]').
Good luck
I have some jquery that will, when a button is clicked, switch a class from a button to a different class (i.e. on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.
https://jsfiddle.net/myfb44yu/
This is the problematic javascript.
$(document).ready(function(){
$('.first').click(function(){
alert('works');
$('#testButton').toggleClass('first', 'second');
});
$('.second').click(function(){
alert("works");
$('#testButton').toggleClass('second', 'first');
});
});
The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.
Your main issue here is a syntax error in regards to your .toggleClass, but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.
An overview of jQuery Event Bindings
Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.
The toys in this example would be your .first and .second elements.
This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.
So, if you do $('.myClass').click();, then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.
Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event.
The Solution
$(document).on("click", ".first", function() { } );
This is known as event delegation.
In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.
Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first.
Hope this helps.
EDIT: As I was typing, JHecht left a good answer that points out the same issue I outlined above.
N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working.class selector
Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second
instead you can write as following
check this snippet
$(document).ready(function() {
var firstElements = $('.first')
var first = firstElements[0];
var secondElements = $('.second');
var second = secondElements[0]
$("#testButton").click(function() {
alert('works');
$(this).toggleClass('first').toggleClass('second');
});
});
.first {
color: red;
}
.second {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
Hope it helps
Ho about this solution. Hope it helps!
$(document).ready(function(){
$("#testButton").click(function(){
if($(this).prop("class") === "first"){
alert('first');
$(this).removeClass("first").addClass("second");
}
else if($(this).prop("class") === "second"){
alert("second");
$(this).removeClass("second").addClass("first");
}
});
});
.first{
color: red;
}
.second{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
I hope that what I am about to say makes more sense than I feel it does.
Your issue is that when you assign the click events, there is not currently an element that has a class of .second.
Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.
A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.
$(function() {
$(document).on('click', '.btn-first,.btn-second', function() {
//here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
//Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
$(this).toggleClass('btn-first btn-second');
});
});
.btn {
padding: 4px 8px;
border-radius: 3px;
border: 1px solid grey;
}
.btn-first {
background-color: green;
border-color: green;
}
.btn-second {
background-color: orange;
border-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='btn btn-first'>Hi</button>
</div>
A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.
$(document).ready(function(){
$('.first').click(function(){
$('#testButton').toggleClass('first second');
});
$('.second').click(function(){
$('#testButton').toggleClass('first second');
});
});
.first { border: thick outset green;}
.second { border: thick inset red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="first">This paragraph has first class</p>
<p class="second">This paragraph has second class</p>
<button type="button" id="testButton" class="first">this button starts out first class</div>
The script can then be simplified by combining multiple class names in a single selector, leaving just:
$(document).ready(function(){
$('.first, .second').click(function(){
$('#testButton').toggleClass('first second');
});
});
Make a neutral class that the buttons both share (.btn).
Then add one of the state classes to each button (.first or .second).
Delegate the click event to the neutral class only ($('.btn').on('click',...).
Then toggle both state classes on this ($(this).toggleClass('first second');)
The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
There is an example with the images outside of buttons and another example that doesn't toggle classes around.
SNIPPET
$('.btn').on('click', function() {
$(this).toggleClass('first second');
});
/* OR */
$('.alt').on('click', function() {
$('.img').toggle();
});
.first > .one {
display: block;
}
.first > .two {
display: none;
}
.second > .one {
display: none;
}
.second > .two {
display: block;
}
.first + .one {
display: block;
}
.first + .one + .two {
display: none;
}
.second + .one {
display: none;
}
.second + .one + .two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Use jQuery with CSS</p>
<button class='btn first'>
<img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<button class='btn second'>
<img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<br/>
<br/>
<button class='btn first'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<button class='btn second'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<p>Or use only jQuery no CSS</p>
<img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
<img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
<button class='alt' style='display:block;'>Toggle</button>
So I don't get why this isn't working. I want to show a Div when another div has a value. I got this code from stackoverflow and it's pretty simple. But it doesn't work for me. No console errors..
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
});
If the html value of .txt is larger then 0 then show btn-01.
But it doesn't. In my web inspector it just says:
<div style="display: block;" class="btn-01"><p>Things</p></div>
If I remove the script it says:
<div class="btn-01"><p>Things</p></div>
So it does do something. I tried changing the show to hide. But no go.
<div style="display: none;" class="btn-01"><p>Things</p></div>
I tried:
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').addClass('showme);
}
});
btn-01 css:
.btn-01 {
background: #f60;
color: #fff;
border-radius: 2px;
padding: 5px;
text-align: center;
margin: 40px auto 0px auto;
width: 90%;
}
But that didn't work either. Does anyone know whats going on here?
Maybe I should work with an else statement? Help would be much appreciated.
JsFiddle
You need to either set the button to display none prior to the window loading or add an "else" statement to hide the element:
.btn-01{
display:none;
}
OR
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
else
{
$('.btn-01').hide();
}
});
See the fiddle: https://jsfiddle.net/r89gg7tp/
IMPORTANT TO CONSIDER
If you have entered a line break between the starting and closing tags of the element, this will add to the length. You need to set the txt div to be in the following format:
<div class='txt'></div>
It may be better to change your function to this:
$(document).ready(function(){
if ($(".txt").html().trim(' ').length > 0) {
$('.btn-01').show();
} else {
$('.btn-01').hide();
}
});
This way you trim the whitespace before checking.
See the second fiddle: https://jsfiddle.net/r89gg7tp/3/
You need to hide the btn-01 with a "display:none" in the stylesheet and then execute your script.
I think you are having a "display:none !important" which is overriding the jquery show() function inline style.
This might help you.
$(document).ready(function(){
if (!$.trim($(".txt").html())){
$('.btn-01').addClass('showme');
}
});
Please let me know if you've any queries.
You can use .contents() with .toggle():
$(document).ready(function() {
$('.btn-01').toggle($(".txt").contents().length > 0);
});
.btn-01{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="txt">
<h3>Things Title</h3>
</div>
<div class="btn-01">
<p>Things</p>
</div>
You guys where all right. I needed to place the code in some Session file (Ajax). Now its working with the original code and even some that you provide.
Thanks!
I am making a panel of photos/text. All the panels will have an overlay color on them except the first one which has an active class on page load which removes the overlay. As you hover over the second/third etc panels, the overlay active class will remove from first panel and go onto the one that is hovered.
Right now it is only active on page load, I can't seem to get the class off the first div and onto the second div on hover.
if ( $(".overlay:first") ){
$(".overlay:first").addClass("active");
}
else {
if ( $(".overlay:not(:first)").hover ){
$(".overlay:first").removeClass("active");
}
}
https://jsfiddle.net/egdkuh16/3/
There is no need to use JavaScript or jQuery for this. It's best used in CSS with the :hover pseudo-selector. It's also much easier today.
.overlay:first-child {
background: white;
}
.overlay:first-child:hover {
background: gold;
}
If you insist on using jQuery, you can try this
$(".overlay:first").on("mouseover", function() {
$(this).addClass("active");
}).on("mouseout", function() {
$(this).removeClass("active");
});
.active {
background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overlay">First overlay class</div>
<div class="overlay">Second overlay class</div>
This approach is highly frowned upon though
In jQuery, you could do it like this:
$(document).ready(function() {
// Make the first active
$(".overlay:first").addClass("active");
// On hover remove all active classes from .overlay
// and add .active only to the one that is hovered
$(".overlay").hover(function() {
$(".overlay").removeClass("active");
$(this).addClass("active");
});
});
but Richard Hamilton's answer is much better and cleaner.
You can use jQuery's on. For example:
$(".overlay:first").addClass("active");
$(".overlay").on("hover", function(){
$(this).addClass("active");
$(".overlay:first").removeClass("active")
});
I have this HTML:
<div id="parent1" class="article">
<div class="action"></div>
<div id="exp1" class="expand"></div>
</div>
<div id="parent2" class="article">
<div class="action"></div>
<div id="exp2" class="expand"></div>
</div>
and CSS:
.article:hover .action {
z-index:1000;
}
.expand {
display: none;
}
action {
background: url(../images/down.png) 0 0 no-repeat;
z-index: -999;
}
.collapse {
background: url(../images/up.png) 0 0 no-repeat !important;
z-index: 1000;
}
and Javascript:
$(".article").click(function() {
$(this).find(".action").toggleClass("collapse"); // works onclick div article
????????? // when press parent1 if parent2 pressed before ???????.find(".action").toggleClass("collapse");
$("#exp2").hide(); // if previously open
$("#exp1").toggle(300);
}
Now I need jQuery for onclick parent1 to toggleClass action in parent2 but only if prevously toggled to collapse.
There are a number of ways to do it. Normally I would store a local variable that holds the state of the drop down (boolean) and just check that.
With jQuery, since you are already using hide(), you can use:
if ($("#exp2").is(":hidden")) {
// Show content, set arrow to up.
$("#exp2").removeClass("expand").addClass("collapse");
}
else {
// Hide content, set arrow to down.
$("#exp2").removeClass("collapse").addClass("expand");
}
The toggle would make more sense if you were just adding and removing a class. Here you are alternating classes. Using addClass() and removeClass() makes it very clear what you are doing.
I take a guess here but I think you want to close any open .article and open the one you clicked on.
$(".article").click(function() {
// see explanations 1 and 2 below
$('.article.active').removeClass('active').find('#exp1').hide();
// see explanation 3 below
$(this).addClass('active').find('#exp2').show();
}
You can change the code to suit your need but so you understand it:
When we click on an .article, we look for any other .article with a specific class (.active in my exemple). Technically, there will likely be only one of .article.active
We remove its .active class and do whatever on it or its child
We finally do whatever on the clicked article