What is the best way to enable click functionality on the SVG Object and smoothly scroll to anchor using jQuery?

My SVG is embedded using an object tag and includes CSS3 hover animations. However, I am facing issues when trying to hyperlink the SVG with hover animation as it interferes with clicking actions. I chose not to use the long SVG path code for better code organization.

The JavaScript provided below makes the SVG clickable, but it doesn't navigate to the desired anchor # for scrolling later on the page. Is there a way to combine these two click functions effectively?

I understand this setup may seem messy at the moment!

HTML

<object id="example" type="image/svg+xml" data="/images/icon.svg"></object>

Inside the SVG:

<a xlink:href="#top">
    <g class="whole" fill="#fff">
        <rect id="body" x="113.83" y="185.4" width="43" height="49.5" style="stroke:#f36a24;stroke-miterlimit:10;stroke-width:3px" />
        <ellipse id="head" cx="134.96" cy="165.04" rx="14.13" ry="13.92" style="stroke:#f36a24;stroke-miterlimit:10;stroke-width:3px" />
    </g>
</a>

//JS below

<script>
       (function ($) {
           $(document).ready(function () {
               $('svg a').click(function (event) {
                   alert(event.target.parentElement.tagName);
               });
           });
       })(jQuery);

</script>

<script>
    $(function () {
        $('a[href*="#"]:not([href="#"])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });
</script>

Answer №1

It seems like the click functionality is working fine, but in order to smoothly scroll to another anchor, an additional step needs to be taken. You just need to add this code snippet within your click event handler:

$('html, body').animate({
      'scrollTop': $('#scrollTo').offset().top
}, 2000);

For a demonstration, you can check out this example here.

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

Creating route in Node.js using the forEach method

While attempting to create routes for each ID using a forEach loop, I encountered a problem where the second route would not run and the application would continue loading until a timeout is reached. I have checked all the expected values and everything se ...

Issue with jquery .val() function not functioning as expected

I am experimenting with the jQuery .val(value) function to set the value of an attribute using the code snippet below. <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">< ...

Refresh doesn't refresh

function updateImage(){ $("#fileImg").attr("src","image.jpg"); $('#fileImg').fadeIn('slow'); } function updateContent(){ $.get('content.php', function(data) { $('#content').html(data); $('#content&apos ...

Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location. The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red ...

Enrolling in the system and working with Java servlets

Registration forms on my website trigger a Java Servlet to check the database for existing usernames or emails. How can I ensure the client receives a response from the Servlet indicating whether the registration was successful or not? The desired outcome ...

Customizing Background Color in React Bootstrap Table Based on Value

Having a little issue that's causing me some trouble. I have a React Bootstrap Table displaying data from an API, and I'm looking to enhance it by changing the row color to green if a specific value is greater than zero. Here is an example: const ...

Reconfigure the Node application using Express to seamlessly access modules through route files

I recently created a basic app using npm express. After generating the app.js file, I attempted to add new modules but encountered an issue where I couldn't access them in the route files. For example, when trying to utilize the 'request' mo ...

Is there a way for me to incorporate a function in this script that allows for cycling through URLs in a predetermined order by clicking a button?

Is it feasible to incorporate a click button cycle URL function that alternates between URLs in a specified order to this script? <script type="text/javascript> var urls = new Array(); urls[0] = "google.com"; urls[1] = "amazon.com"; var random = M ...

Properly accessing a JavaScript object acquired from a JSON file

I have a JSON file with data for 4 different items. Once I parse the JSON file, I see the output below. At that point, do I now have a JavaScript object? My goal is to access each item and add them to a plain object. How can I achieve this? The resulting ...

I'm wondering how I can design a utility function within my Redux module that can extract a specific subset of read-only data from the current state

I am currently utilizing redux to create a "helper function" inside my redux module that is responsible for fetching filtered data from the state based on a specified index. This specific data will be used to generate a form consisting of inputs depending ...

Clicking a remote link in Rails 3 will initiate a different request upon the second click

My Rails application was functioning smoothly until I decided to upgrade my ruby version, rubygems, and all my gems. Most of the links in my app are remote links. The first time I click on a remote link, Fancybox opens up the new content correctly. Howeve ...

Customize the style based on the state using styled components

I am currently working with a function component that looks like this: const Navbar = ({setNav, nav}) => { const [justify, setJustify] = useState('space-around') //get localStorage const user = JSON.parse(localStorage.getItem('user& ...

Tips on choosing vml elements using jquery or vanilla javascript

I am trying to select a VML element using jQuery without relying on 'id' or 'class', but my attempts have been unsuccessful so far. <v:oval id="vmlElement" style='width:100pt;height:75pt' fillcolor="red"> </v:oval> ...

Executing a function from a JavaScript file within Robot Framework

It is possible to run javascript from a file. Run JavaScript ${CURDIR}/js_to_run.js However, I am wondering how to call a function by its name from this file? ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

Use jQuery to apply CSS to a div only when it becomes visible on the screen

I created a single page HTML with scrolling functionality. The structure of my divs - home and home2 - is as shown below. Both have a height of 100%. I am looking to add CSS to the second div (home2) using jQuery only when it becomes visible to the user in ...

Tips for targeting the second field upon clicking the next button in React Native

I need help implementing a feature where, when a user clicks on the "Next" button, the focus shifts to the next field without using the ref method. Can someone assist me in achieving this goal without using ref? Thank you. ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

When using the v-for directive to display all elements of an array, only the information of the clicked array should be listed when using the

I am facing an issue with my array of locations. There are 2 divs in play - one containing the list of locations and the other displaying additional info when a location is clicked. The problem arises when I click on a specific location, let's say Sc ...