Switch up the attribute of an SVG element using jQuery

It has come to my attention that addClass and removeClass cannot be used with SVG, requiring the use of attr instead. However, I am facing a challenge in toggling an attribute of an SVG using jQuery. To see the specific issue I am encountering and my attempted solution, please check out my JSFiddle. My goal is to toggle the rotation of an arrow upon click (refer to the commented-out part of the click function in the JavaScript section). Does anyone have an alternative approach for achieving this?

Here's a snippet of my HTML:

<div class="col-md-3 col-sm-4 sidebar">
                <div class="title-region">
                    <a href="">Current Page</a>
                    <svg class="down-arrow mobile-only" width="17px" height="10px">
                        <use xlink:href="#down-arrow"></use>
                    </svg><!--end hamburger-->
                </div><!--end title-region-->
                <div class="mobile-zipped">
                    <ul class="sidebar-block children">
                        <li><a href="">Child One</a></li>
                        <li><a href="">Child Two</a></li>
                        <li><a href="">Child Three</a></li>
                    </ul>
                    <ul class="sidebar-block siblings">
                        <li><a href="">Sibling One</a></li>
                        <li><a href="">Sibling Two</a></li>
                        <li><a href="">Sibling Three with a super long title</a></li>
                        <li><a href="">Sibling Four</a></li>
                    </ul>
                </div><!--end mobile-zipped-->
            </div><!--end sidebar-->

CSS snippet:

    .sidebar {
  position: relative;
  /*width:270px*/
  height: auto;
  display: inline-block;
  /*margin-right:60px;max-width:25%*/
}

.sidebar .title-region {
  position: relative;
  height: auto;
  background: #005DAA;
  width: 100%;
  padding: 15px;
}

.sidebar .sidebar-block {
  padding: 15px;
}

.sidebar ul {
  list-style-type: none;
}

.sidebar .down-arrow {
  float: right;
  margin-top: 8px;
  fill: #00305e;
}

The JavaScript code can be found in the provided JSFiddle. Any assistance on resolving this issue would be highly appreciated!

Answer №1

Check out the live demo.

var classes = accordionArrow.attr('class').split(' ');
if ($.inArray("flipped", classes) != -1) {
    //Removing duplicate "flipped" classes using jQuery.grep()
    classes = $.grep(classes, function (element) {
        return element !== "flipped";
    });
} else {
    classes.push("flipped");
}
accordionArrow.attr('class', classes.join(' '));

Answer №2

When looking to toggle the flipped class on the accordianArrow, you can take a traditional approach with handling classes:

var flippedClass = /\bflipped\b/;
var currentClasses = accordianArrow.attr("class");
var updatedClasses = currentClasses.replace(flippedClass, '');
if (currentClasses === updatedClasses) {
    // Class not present; add it
    currentClasses += " flipped";
} else {
    // Removed class, ensure no extra whitespace is left
    currentClasses = $.trim(currentClasses);
}
accordianArrow.attr("class", currentClasses);

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

Angular material input featuring an additional component

Trying to integrate an additional text element next to an input using angular-material. The goal is to replicate the functionality of bootstrap's .input-group-addon: The closest approach achieved so far can be seen in this example: <md-content la ...

Semantic UI dropdown field not displaying selected option text

I've encountered an issue while working with React Semantic UI. I'm trying to render a dropdown and have configured it so that the selected option's text should display in the field. However, when I choose an option from the dropdown, instea ...

Side-to-Side Bootstrap Display Panel

I have been attempting to customize a Bootstrap panel to create a horizontal version, but I am struggling to align the panel heading vertically with the content in the panel body. I believe it may be related to clearing the divs. Front-end development is ...

Using jQuery and AJAX to dynamically add data to POST parameters

Hello, I have a question that may sound like one from a newbie. I am trying to figure out how to insert a variable into a parameter for a POST request instead of simply writing the number in directly: var x = 3; id=(the var x needs to be here)&appid=4 ...

The jQuery .val() function does not function properly when using 'this'

This is an example with a textarea: <textarea id='ta' onkeydown='down(this)'></textarea> and here is the accompanying JavaScript code: <script> function down(input) { alert(input.val()); // not functioning ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

Modify the color of the text input border upon interaction using CSS

Changing text input border color using CSS upon clicking Hey there! I have a text field in my HTML: <input type="text" value="test" id="ff"> Currently, I am using the following CSS to define its border: #ff { border: 1px solid #000; } I would ...

The issue occurs when using z-index: -1 in Google Chrome causes links to malfunction

Recently, I encountered an issue with Chrome. When I applied a z-index of -1 to a position: relative; unordered list, the links within it became unclickable. You can see an example at http://jsfiddle.net/raLnx/ using Chrome 20.0.1132.47m. There is no pro ...

Practical Tip for jQuery - Storing DOM Element in a Variable for Consistent Usage Across Your Codebase

As I was searching for some Jquery best practices, I came across this gem. Source: // Storing the live DOM element in a variable var elem = $("#elem"); // Setting an element's title attribute using its current text elem.attr("title", elem.te ...

Exploring the world of JQuery tabs and interactive forms

So, I've encountered a rather perplexing issue that I could use some help with... Currently, I'm working with JQuery ajax tabs. These tabs are dynamic and allow for multiple additions. The content is loaded through Ajax, meaning the same content ...

What is the best way to apply padding to the top of a div when it is positioned below another div?

Observing the minimal spacing between the divs AboutDogs and AboutCats, I decided to apply padding-top: 20px to the AboutCats to create a visual distinction. However, I encountered a scenario where only AboutCats exists without any other div above it. In ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

What is the best way to position three SVG files in the center of a webpage?

I want to combine three separate SVG files to create one single graphic. The first SVG file is a red triangle, the second is a blue circle inside the triangle, and the third is a purple rectangle beneath the triangle with a little space in between. My obje ...

Ways to prevent a background image from centering at a designated width

Is it possible to prevent a background image from centering at a specific width? To demonstrate the issue, try narrowing the width of the website linked below until scroll bars appear. Take note of how the background image stays centered while other eleme ...

Bringing in CSS variables to a Typescript document

In order to streamline the styling process for our app, we have established a theme.css :root file containing a set of commonly used variables that can be accessed across all other .css files. However, some of our older code follows a similar structure bu ...

Adjust the top margin of a div to match the height of the screen within an iframe, ensuring cross-browser

Trying to adjust the margin-top of a div to 100% of screen height within an iframe seems to be causing issues with jQuery, as it either returns 0 or inaccurate values. While CSS3's 100vh can work as an alternative, it may not be supported in older an ...

Implement the stylesheet to accommodate different screen sizes while still maintaining the integrity of the standard screen

I've been searching through various discussions and questions, but I have not found the exact solution to my issue. The website I created fits within a 960px block for optimal viewing on iPads, but now I need a stylesheet to be applied when the scree ...

"Exploring the features of HTML5: Adjusting audio playback speed and tracking

With an HTML 5 audio tag, I have calculated the start and end times of each word. As the audio plays, I track the current time and compare it to the start and end times of each word to highlight any matching words. Everything is working well so far. Now, ...

Understanding the breakpoints in Media QueriesExploring the intric

I have established these breakpoints X-Small devices (portrait phones, less than 576px) @media (max-width: 576px) { body { background-color: red; } } Small devices (landscape phones, less than 768px) @media (max-width: 768px) { body { ...

Design Forms with a Revolutionary UI Framework

Our team is getting ready to tackle the challenge of designing complex forms using HTML. Are there any reliable and versatile UI frameworks out there that can help us with this task? What would be the most effective way to begin this project? We need a fr ...