Targeting sibling´s children

Hi there,

I have the following markup:

<div class="preguntas-wrapper">
                      <article>
                                <p>P - He comenzado a estudiar el texto y tengo la sensación de que no estoy entendiendo nada. Sin embargo parece que la información llega a una parte de mi mente que no puedo identificar con claridad.<span class="ver-respuesta">respuesta</span></p>
                                <div>R - La información que aparece en Un Curso de Milagros ha sido transmitida en una frecuencia mental muy elevada. La mente del alumno no suele estar afinada en esa frecuencia cuando comienza el estudio en profundidad del Curso. Por lo tanto, es necesaria una sintonización que le permita acceder al significado de las palabras que aparecen en el texto. Esta sintonización se produce cuando el alumno continúa con la lectura y la práctica de los ejercicios, puesto que la mente tiende a adaptarse a la vibración de los pensamientos que se aceptan en ella, aunque en un principio éstos parezcan estar inducidos desde afuera. Es habitual que después de un tiempo, al realizar una segunda lectura de algo que no se comprendió por primera vez, esta información se entienda ahora con mayor claridad.</div>
                            </article>
                            <!-- -->
                            <article>
                                <p>P - Leo el ejercicio por la mañana y aunque la frase es corta y sencilla me cuesta recordarla durante el resto del día.<span class="ver-respuesta">respuesta</span></p>
                                <div>R - Tu mente lee el ejercicio desde los aspectos razonantes del cerebro, o ego. La información que lee no corresponde al mundo de los sentidos físicos, que es lo único que el ego puede comprender. Como no dispone de una referencia sólida con la que relacionar la información que lee, ésta no se integra consistentemente en la memoria, por lo que es fácil que se olvide. Según se avanza en el proceso de aplicación práctica con los ejercicios, este problema comienza a desaparecer. Mientras esto no ocurra, la solución más práctica es apuntar la frase del ejercicio en algún lugar y llevarlo consigo durante el día para recordarlo en el caso de que se olvide. Saber esto y no realizarlo es una forma de resistencia al cambio.</div>
                            </article>
</div>

and the following Jquery:

$(document).ready(function(){

               $('.preguntas-wrapper > article > div').addClass('magic');		
		
		if($('.magic').is(':visible')) {
			  $('.ver-respuesta').hide();};

});

This Jquery will hide all instances of the span.ver-respuesta as long as there is one div.magic visible. Now, how could I target just the span.ver-respuesta, children to a <p> tag, previous to the div.magic siblings to the <p> tag which is parent to the span.ver-respuesta? What would be the right syntax?

Thx a million in advance.

Whitecreek.

Let’s se if I’m able to put it in a simpler way… cause it’s driving me a little mad

markup:


<article>
   <p class="box1">some text<span class="miau">show</span></p>
   <div>some more text</div>
</article>

<article>
   <p class="box1">some text<span class="miau">show</span></p>
   <div>some more text</div>
</article>

this would work, meaning it would hide span.miau. Logically, it hides all instances of span.miau in the page as long as there is any of the divs showing:

jquery


$(document).ready(function(){

var answer = $('article > div');
if(answer.is(':visible')) {
	$('.miau').hide();
        };

});

and this wouldn´t target just the previous instance of span.miau, actually it hides nothing, no matter if there is a div visible or not:


$(document).ready(function(){

var answer = $('article > div');
if(answer.is(':visible')) {
	$(this).prev('.box1').children('.miau').hide();
        };

});

And I don’t get it. I can’t see what’s wrong whith the second chunk of jquery. Any help would be greatly appreciated…

Regards.

Hi whitecreek,

If I am understanding you correctly, you are trying to do something like this:

var answer = $('article > div');
answer.each(function(){
  $(this).prev('.box1').children('.miau').hide();
});

Hope that helps.

Hi there Pullo, man, always to the rescue… thx for answering

Well, not exactly, If I’m getting it right your code will, for every (each) instance of answer, it will hide any existing span.miau being this span children to any p.box1. p.box1 and answer are siblings.

My goal is to hide any instance of span.miau only when the next instance of answer is visible. When answer is not visible the previous instance of span.miau will be.

This is actually a FAQS section in a website. <p class=“box1”> would be the question itself. The div (answer) would be the answer to the question which is hidden when the page loads. And span.miau would work as a button to make the answers show. When the answer shows I’m trying to hide the button. I have the jquery to make the answers show and hide already set up, but I don’t seem to be able to hide the button…

I would post the url for the page, but I’ve quite simplyfied the code for this post and I didn’t want to make a mess of things… which I’m not sure I haven’t done already!!! :slight_smile:

Something like this maybe?

var answer = $('article > div');
$(".miau").each(function(){
  var nextAnswer = $(this).parent().next();
  if(nextAnswer.is(':visible')){
    $(this).hide();
  };
});

This will only hide elements of the class “.miau” if the adjacent sibling of their parent element is visible.

Yep, that kind of work on page load, but it doesn’t when you start showing/hiding answers (divs). I tried putting that into a function out uf the document.ready and refering to that function inside the document.ready, within the click event that hides/shows without success. It seems to hide buttons but not always and it never shows them back.

Here’s the function I made:


function silent_button() {
					
			var answer = $('.preguntas-wrapper > article > div');
				$(".ver-respuesta").each(function(){
 				 var nextAnswer = $(this).parent().next();
  					if(nextAnswer.is(':visible')){
    				$(this).hide();
  					} else if (nextAnswer.is(':hidden')) {$(this).show();};
					});
		
		};
 

Here’s the url for the page. You’ll see the jquery document (MAIN-jquery.js) is a bit more complex but I guessed it would make things easier to spot:

http://www.ficoprieto.com/adpi-faqs/faqs-adpi.php

Hi,

So let’s approach this from another angle.

You have a FAQ page with a bunch of questions and the relevant answers.
The answers are hidden by default and can be revealed by clicking a “Show answer” button.

Then what?

Should any of the answers be visible on page load?
Should the “Show answer” button vanish when you reveal an answer?
Should you be able to close an open answer by clicking where the button was before it vanished? (you can now)
Should the user be able to have multiple answers open at once?

Let me know the answers to these questions and I’ll see what I can come up with.

Hi there

1.- Just the answer to the first question should be visible on page load, as it is now

2.- Yep, the “show answer” button should vanish when an answer is revealed, and it should show back when the answer is hidden. The thing here is that, originally there wasn’t going to be any “show answer” button. It was going to be the question itself , a <p> tag in this case, the element triggering the show/hide event for the answer. That is why I have it set up this way right now. Finally the client changed his mind in this regard and decided he wanted a “show answer” button.

3.- Yes, you can now because the question, and not the button, is what triggers the show/hide event. I thought it might not be necessary to change that.

4.- Only one answer should be visible at a time. So only one button should be hidden in any situation.

Thx Pullo.

Hi,

I would do it like this:

var $answers = $('.preguntas-wrapper > article > div');
var $questions = $('.preguntas-wrapper > article > p');

$answers.hide();
$questions.append('<span class="ver-respuesta">respuesta</span>');

var $revealButtons = $('.ver-respuesta');

$revealButtons.on("click", function(){
  $revealButtons.show();
  $answers.slideUp(500);
  var answer = $(this).parent().next(),
      button = $(this);
  answer.slideDown(500);
  button.hide();
});

Here’s a demo.

Hope that helps.

Yes, that helps. Neat, clean and easy to understand. Choosing the button instead of the question to show/hide answers really simplifies things after all.

I take it from there to make the first answer visible on page load.

Thx again for your time & effort Pullo. Cheers buddy.

Best regards,

Whitecreek.

Oops, sorry, forgot about that last point.
You can acheive that by using jQuery’s trigger() method.

Glad the rest works :slight_smile:

And finally, the demo link, already set up so the first answer is visible on page load using trigger() method:

http://www.ficoprieto.com/adpi-faqs/faqs-adpi.php

The Jquery chunk as ir is right now:


                var $answers = $('.preguntas-wrapper > article > div');
		var $questions = $('.preguntas-wrapper > article > p');

			$answers.hide();
			$questions.append('<span class="ver-respuesta">respuesta</span>');

			var $revealButtons = $('.ver-respuesta');
			var starter = $('.preguntas-wrapper > article:first-child .ver-respuesta');

			$revealButtons.on("click", function(){
  				$revealButtons.fadeIn(300);
  				$answers.slideUp(200);
  				var answer = $(this).parent().next(),
      			button = $(this);
  				answer.slideDown(500);
  				button.fadeOut(300);
				});
			starter.trigger('click');

Sweeet. Thx again Pullo. Talk soon.

Best regards,

Whitecreek

Looking good :slight_smile:
Thanks for taking the time to report back.