Manipulating active classes on different divisions with JQuery

I've completed this code so far:

<div class="yearly-archive">
    <p> YEAR -  <span class="archive-year year-active"> 2014 </span> / 
        <span class="archive-year"> 2013 </span> /
        <span class="archive-year"> 2012 </span> /
        <span class="archive-year"> 2011 </span> /
        <span class="archive-year"> 2010 </span>
    </p>
</div>

<div class="news-container news-active" id="news-2014"></div>

<div class="news-container" id="news-2013"></div>

<div class="news-container" id="news-2012"></div>

<div class="news-container" id="news-2011"></div>

<script>
$('.archive-year').click(function() {
    $('.archive-year').removeClass('year-active');
    $(this).addClass('year-active');
});
</script>

Fiddle: http://jsfiddle.net/codestor/C7xj6/2/

I'm working on implementing the following functionality:

When the user clicks on 2013, the news-active class of news-container should switch to the div with the id news-2013

Any assistance would be greatly appreciated.

Answer №1

To achieve a similar outcome as with the links, you must extract the text from the clicked link and use it to create your id selector. Once you have identified which link was clicked on, retrieve the text inside the link using $(this).text() and ensure there are no extra spaces with .trim(). This will allow you to target the news div by combining the string with

'#news-1' + <link text value>
. Give it a try...

$('.archive-year').click(function() {
  $('.archive-year').removeClass('year-active');
  $(this).addClass('year-active');
  $(".news-container").removeClass("news-active");
  $("#news-" + $(this).text().trim()).addClass("news-active");
});

Fiddle

Answer №2

Retrieve the text that was clicked within a span using the function $(this).text() and then apply a class to the corresponding div element in the following manner:

$('.archive-year').click(function(e) {
        e.preventDefault();
        $('.archive-year').removeClass('year-active'); // remove class from all spans
        $(this).addClass('year-active'); // add to the currently clicked span
        $(".news-container").removeClass("news-active"); // remove class from all div elements

        $('#news-'+$.trim($(this).text())).addClass("news-active"); // add class to the corresponding div
    });

The key step lies in the code snippet:

$('#news-'+$.trim($(this).text())).addClass("news-active");
where the text inside the span is fetched, trimmed, concatenated with the prefix news-, and the class news-active is added to it.

VIEW UPDATED FIDDLE

Answer №3

   $(document).on('click', function(event){
        if($(event.target).hasClass('archive-year') && $(event.target).text() == ' 2013 '){
            $(div[class='news-container news-active']).attr('id', 'news-2013');
        }
    })

Answer №4

Here is a suggestion for you:

$(document).ready(function(){
  $('.archive-year').on('click', function() {
     $('.year-active').removeClass('year-active');
     $('.news-active').removeClass('news-active');
     $(this).addClass('year-active');
     $('.news-container[id*="'+ $.trim(this.textContent) +'"]').addClass('news-active');
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The correct functionality of canvas coordinates may become unreliable once CSS has been implemented

After successfully setting up my drag and drop game in canvas, I decided to make my canvas responsive by adding the following code to my css file: #canvas { width:100% } However, this adjustment caused a discrepancy in my coordinates. Now, when I cli ...

Responsive design is key in ensuring that Bootstrap columns adjust accordingly

I am attempting to create a responsive block in the center of my webpage with the help of Bootstrap. However, I am having trouble getting the columns to respond correctly to my bootstrap setup. Can anyone point out what I might be doing wrong? <lin ...

Utilize a DIV element to apply a class to CKEditor

Currently, I am utilizing CKEditor in DIV mode instead of an IFRAME and I am facing a challenge in assigning a class to the editor itself. While I have managed to add classes to elements within the editor, figuring out how to assign one to the editor itsel ...

Restrict the size of an image within a div by setting a maximum height and allowing the width

While this code snippet functions perfectly in WebKit browsers, it encounters issues when used in IE and Firefox. Unfortunately, due to other necessary functionalities, using the img tag is essential, making background-image an unviable option. Code Snipp ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Is there a way to prevent the contents of my div from overflowing beyond my other div?

Hey there! I'm fairly new to this whole web design thing, only a few months in. Currently, I'm in the process of creating a website for my school. However, I've hit a bit of a snag with different div containers holding various parts of my ...

Should all variables be retrieved from the database and stored as session variables, or is this considered a poor practice?

I implemented the jQuery load function to only refresh the body content of my website, while keeping the header consistent. Instead of repeatedly querying the database for the same information across multiple pages, could I potentially increase the initi ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Oops! There seems to be a problem with your AngularJS/JavaScript code. The error message is "Uncaught ReferenceError:

As I venture into the world of AngularJS and JavaScript, I am working on creating a 'blog' using these technologies. Here is my HTML view code- <div ng-controller="Controller1"> <form ng-submit="sub()" role="form"> Title: <textar ...

Is it possible to access (event, xhr, options) in .ajaxStart or .ajaxStop using jQuery?

According to the documentation on http://api.jquery.com/ajaxComplete/ .ajaxComplete( handler(event, XMLHttpRequest, ajaxOptions) ) .ajaxStart( handler(event) ) From my own knowledge and testing, it seems that the XMLHttpRequest and ajaxOptions parameters ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

What is the best way to eliminate the bottom border of an input field?

Seeking advice on how to eliminate the border-bottom of an input field when typing starts. .car-list-input { font-family: 'Source Sans Pro', sans-serif; border-radius: 3px; font-size: 14px; font-weight: 400 !important; height: 35px; ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

What could be causing my col-x to not function correctly in Bootstrap?

I am trying to modify my Bootstrap navbar by adding a Login button, but I encountered an issue. When I use col-x classes inside the navbar to separate elements equally, they only cover 50% of the width and no more. However, using col-x classes outside the ...

The media query will only impact elements and classes within the index.html file, and will not apply to any other

As I strive to optimize my website for mobile devices, I am encountering an issue with my media queries. The classes don't seem to respond appropriately on any page other than the index.html, and I'm struggling to identify the root cause. Index. ...

Tips for preventing a page from automatically scrolling to the top after submitting a form

Recently, I set up a form where users can input values. The form is set to submit either on change or when the user hits enter, depending on which value they want to update. However, after the values are submitted, the page automatically jumps back to the ...

Converting a Powershell array into an HTML format

I have three arrays that I need to display on an HTML page: foreach($item in $array1){ // write array data to HTML } foreach($element in $array2){ // write array data to HTML } foreach($value in $array3){ // write array data to HTML } What is the ...

Guide on using timestamps in PHP

I am struggling to incorporate the current date and time of the SO-NUMBER that the user is entering. The issue I'm encountering lies within the IF..ELSE loop, it only updates one column in the database, which is the "samplerecived" column even if I ...

Initiating a animation prior to the execution of JQuery's load() function

I'm currently exploring the functionalities of JQuery's load() function and I am puzzled as to why a particular animation does not occur prior to the load request. For instance, when I include a script like this: $('#clickme').click(f ...