0

quick easy question for anyone who knows a little jquery.

$(document).ready(function(){
    $('.selected').on('click', function(){

I have a navigation menu that has a class added to each li element when they are clicked (class 'selected' is added). I am trying to change the text inside of another container below the navigation (with class="banner-header") using replaceWith ie

$('.banner-header').replaceWith('Eugene is too cool for school');

However I am getting stuck because the text has to change depending on which navigation menu item is being pressed. I could write a lengthy if statement, but I don't know where to start, please help!

Thanks in advance.

2 Answers 2

1

If your navigation structure is like this:

<ul class="navigation">
    <li>Nav 1</li>
    <li>Nav 2</li>
    <li>Nav 3</li>
</ul>

<div class="banner-slider">Default Text</div>

You can use this script:

$(document).ready(function(){
    $('.navigation li').on('click', function(e){
        $('.banner-slider').html($(e.target).html());
    })
});

Check this demo.

Sign up to request clarification or add additional context in comments.

4 Comments

awesome, love the simplicity. Wondering if you could explain the (e) to me?
also what If I wanted to customise what I want to say instead of having the text from the navigation display? for instance if user clicks 'nav 1' and I want 'You clicked navigation one' to display?
e is for event, responsible for collecting the event data. It is optional, but if you want to get the event data, you have to pass it to your event closure. In this case, you want to know which li is clicked, event.target is what you need.
If you want to customize the text, you only need to modify this code $('.banner-slider').html($(e.target).html()); to something like $('.banner-slider').html('You clicked ' + $(e.target).html() + '.');.
1

You can do something like this: https://jsfiddle.net/jLvppk3f/

HTML:

<ul>
  <li class="menu" data-banner-text="A SELECTED"><a>A</a></li>
  <li class="menu" data-banner-text="B SELECTED"><a>B</a></li>
  <li class="menu" data-banner-text="C SELECTED"><a>C</a></li>
  <li class="menu" data-banner-text="D SELECTED"><a>D</a></li>
</ul>
<div class="banner-header">
    TEST
</div>

JS:

$(document).ready(function(){
    $('.menu').on('click', function() {
        $('.menu').removeClass('selected');
        $(this).addClass("selected");
      $('.banner-header').text($(this).data('banner-text'));
    })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.