jQuery, DOM and on() method - javascript

I have a problem with jQuery, DOM and on() method. This is my div:
<div class="box">
<p class="addBox">Add Box</p>
<p class="remBox">Remove Box</p>
<textarea name="box[]"></textarea>
</div>
And a jQuery code:
$(document).on("click", ".addBox", function(event){
$(this).parent().append('<div class="box"><p class="addBox">Add Box</p><p class="remBox">Remove Box</p><textarea name="box[]"></textarea></div>').children(':last').hide().fadeIn(1000);
});
$(document).on("click", ".remBox", function(event){
$(this).parent().hide(1000).delay(1000, empty());
});
What I'm trying to achieve is a box with two buttons, one of them will make another copy of this box, and the other one will delete the chosen box. Two copies of the box are 'hardcoded' in index file, thus available in DOM from the start.
Buttons do they basic purpose, but DOM structure is getting crazy. If I press the 'add box' link on a newly created box, the new one will show up right after the one I clicked. However, sometimes it will show up at the end of the list. It's the same with 'del box' link, sometimes it deletes only one box, sometimes the one I want and two or three more. What do I do wrong? Thanks!

You probably want .after() (or .before()), but not .append(). That, and your .delay() syntax isn't correct.
$(document).on("click", ".addBox", function (event) {
$(this).parent().after('<div class="box"><p class="addBox">Add Box</p><p class="remBox">Remove Box</p><textarea name="box[]"></textarea></div>').children(':last').hide().fadeIn(1000);
});
$(document).on("click", ".remBox", function (event) {
$(this).parent().hide(1000).delay(1000).remove();
});
jsFiddle example

The reason that you're seeing all of your boxes removed sometimes is that you're appending new boxes to the parents of the .addBox item, which is the box div -- so you're getting boxes nested in boxes, rather than a bunch of .box divs in a row. If you change
$(this).parent().append( ... // removed for clarity
to
$('body').append( ... // the rest of your code
You won't get that improper nesting, and your boxes will correctly remove only themselves.

Related

jQuery.toggle() not working on a div

On a web page we have a list of profiles. On the right hand side of the profile is some text, followed by an arrow img#arrow.
When img#arrow is clicked, we have the following jQuery we hope to run:
However, the corresponding .bottom-sec is not toggling.
jQuery('#arrow').click(function(){
var $parent = $(this).parent();
$($parent).addClass('active');
jQuery($parent +' .bottom-sec').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="profile-right">
<h2>Bob Brown</h2>
<h3>Non-Executive Chairman</h3>
<p>Intially showing text.</p>
<div class="bottom-sec" style="display: none;">
<p>Initially hidden text.</p>
</div>
<img id="arrow" src="/wp-content/themes/wtc/images/icons/down-arrow-circle-hi.png">
</div>
Problem
The problem with your code is exactly what the comment on your question is saying, but he didn't explain anything:
You're combining two different ways of selecting elements. One is with selectors, the other is traversing. You're using them in a way which isn't possible (the $parent + ' .bottom-sec' part). The comment linked to a jQuery page about traversing which you should definitely read! It tells you a lot about how to use traversing functions, which you could use!
Solution
There are multiple solutions to this, but I'll write down the one I think is the best:
First of all, change the HTML a bit. I've removed the element style of .bottom-sec and changed the id of the image to a class, because you have multiple images with the same id on the page, which is not a recommended thing to do. Classes can occur more than once, id's cannot.
<div class="profile-right">
<h2>Bob Brown</h2>
<h3>Non-Executive Chairman</h3>
<p>Intially showing text.</p>
<div class="bottom-sec">
<p>Initially hidden text.</p>
</div>
<img class="arrow" src="/wp-content/themes/wtc/images/icons/down-arrow-circle-hi.png">
</div>
I've reduced the JavaScript to the following. Note that is just reduced to one line, where a click on the .arrow element goes searching for the closest .profile-right parent. If, for whatever reason, you decide to change the HTML and the .arrow element is no longer a child of the .profile-right, this code still works. The only thing it does is toggle an active class on the .profile-right.
jQuery(document).on('ready', function() {
jQuery('.arrow').on('click', function(){
jQuery(this).closest('.profile-right').toggleClass('active');
});
});
The document ready listener was added because of OP's comment.
With CSS, we can use the new .active class to show or hide the element.
.profile-right .bottom-sec {
display: none
}
.profile-right.active .bottom-sec {
display: block
}
Original Code Fix
If for some reason you wanted to use your original code, this is how it should be:
// Nothing wrong about this part.
// Your only worry should be that there could be
// multiple elements with the same ID, which is something really bad.
jQuery('#arrow').click(function(){
// This part is correct, no worries
var $parent = $(this).parent();
// Removed the $(...), because $parent is already a jQuery object
$parent.addClass('active');
// Changed the selector to a find function
$parent.find('.bottom-sec').toggle();
});
You could also combine all of the code inside the listener function to just one line:
jQuery('#arrow').click(function(){
$(this).parent().addClass('active').find('.bottom-sec').toggle();
});
Change your js code like below.
jQuery('#arrow').click(function(){
var $parent = $(this).parent();
$($parent).addClass('active');
jQuery($parent).find('.bottom-sec').toggle();
});
In your event listener you can catch the element (the down arrow) that triggered the event. It will be referred as this.
Then you can go through the DOM tree using .next() and .parent() to access the <div> to toggle.
Note: you may need more functions than the one I explained above.
Note 2: without code or more detailed information, we can't help you further, I will edit this answer if you add details.

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:
HTML:
<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>
Script:
<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>
By the way, info is being fetched from the database in a php while loop.
When the user clicks on .fade-anchor you can use thisto get the element currently selected, you should also use classes instead of ids for multiple elements, like so:
$('.fade-anchor').click(function(e){
e.preventDefault();
$(this).parent('.fade-content').css('max-height','none');
$(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});
You can also check out this jsFiddle with the working version.
Hope it helps.
You can achieve it by e.currentTarget
$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});

Replace multiple elements using replace with in query

I have a textarea and button that I need to replace with new ones. I use replaceWith in jquery to achieve this but it seems that I'm doing it wrongly.
This is my javascript:
<script>
$(document).ready(function () {
$(document).on('click', 'div', function(){
$('textarea, button').replaceWith('<textarea>New</textarea><button>Old</button>');
});
});
</script>
My HTML:
<textarea>Old</textarea>
<button>Old</button>
<div>Replace</div>
Clicking the Replace div should replace both the Old text area and the button with the new ones but for some reason it leads to displaying 2 text areas and 2 buttons.
Tried using $('textarea', 'button') but this does nothing at all.
If per your comments elsewhere you cannot split the two elements apart for text purposes, then alternatively you should ensure that both existing elements share a common parent (e.g. a <div>) and then replace the contents of that parent:
<div id="parent">
<textarea>Old</textarea>
<button>Old</button>
</div>
$('#parent').empty().append(newContent);
Alternatively if you cannot change the downloaded HTML, then within the event handler if you can assume that there are no other matching elements between the "replace" div and the original content:
$(this).prevAll('button').first().remove();
$(this).prevAll('textarea').first().remove();
$(this).before(newContent);
You should separate the two out, to avoid trying to replace both in the same statement.
$('textarea').replaceWith('<textarea>New</textarea>');
$('button').replaceWith('<button>Old2</button>');

Target currently clicked instance of element

I have multiple instances of a button element:
<div id="openambiance" class="openclose leftside"></div>
<div id="opendesign" class="openclose rightside"></div>
<div id="openperform" class="openclose leftside"></div>
They carry different ID's, as clicking on each of them opens different panel. I would like currently open panel to switch its open/close button background, as per definition in .openclose-active. Reality however is, they are all getting affected. My initial code looked like this and I quickly realised why they are all getting affected:
$(document).ready(function() {
$("#openambiance").click(function(e){
$("#hiddenambiance").slideToggle(600,"easeInOutQuint");
$(".openclose").toggleClass("openclose-active");
});
});
So I tried targeting specific elements:
$(this).find(".openclose").toggleClass( "openclose-active" );
That failed, so I went on to .siblings, .next and .parent, but with no luck. They are still either all switched or only previous instances get switched. I'm lost :(
this is the element you are looking for
$(document).ready(function() {
$("#openambiance").click(function(e){
$("#hiddenambiance").slideToggle(600,"easeInOutQuint");
$(this).toggleClass("openclose-active openclose");
});
});
You are clicking on the button which has the class openclose, so you need to toggle the class for this element not for any of its descendants

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

Categories

Resources