简体   繁体   中英

How to make an inline svg clickable in html/css to use onclick in javascript?

I have an inline svg in my html:

<svg id="nav-search-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32.2 32.2"><path d="M19 0C11.8 0 6 5.8 6 13c0 3.1 1.1 5.9 2.9 8.2l-8.6 8.6c-0.5 0.5-0.5 1.4 0 2 0.5 0.5 1.4 0.5 2 0l8.6-8.6C13.1 24.9 15.9 26 19 26c7.2 0 13-5.8 13-13S26.2 0 19 0zM19 24C12.9 24 8 19.1 8 13S12.9 2 19 2 30 6.9 30 13 25.1 24 19 24z"/></svg>

I want to make another element visible or hidden on clicking the svg. Here's the javascript I use to do this:

let searchIcon = document.querySelector('#nav-search-icon')
let searchBar = document.querySelector('#search-bar')

searchIcon.onclick = function() {
    if (searchBar.style.visibility === 'hidden') {
        searchBar.style.visibility = 'visible'
    } else if (searchBar.style.visibility === 'visible') {
        searchBar.style.visibility = 'hidden'
    }
}

The javascript code does not work. I think the reason it does not work is that the svg element is not clickable (the icon of my mouse does not change from pointer to hand on hovering over the svg). I've tried adding pointer-events="all" to the svg element and also to the path element inside the svg element. I've also tried adding pointer-events: all; to the CSS. None of this worked.

**EDIT: ** I've looked at questions about making the svg link clickable (by adding an <a> tag outside the svg element). I don't want to have a link to another page. I want onclick to work for the svg element.

I made a few changes to the JS , but wrapped the SVG inside of an <a> tag and added the onclick() to that, like so:

 searchClick = function() { let searchIcon = document.querySelector('#nav-search-icon') let searchBar = document.querySelector('#search-bar') if (searchBar.style.display === 'none') { searchBar.style.display = 'block' } else { searchBar.style.display = 'none' } }
 <a href="#" onclick="searchClick();"><svg id="nav-search-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32.2 32.2"><path d="M19 0C11.8 0 6 5.8 6 13c0 3.1 1.1 5.9 2.9 8.2l-8.6 8.6c-0.5 0.5-0.5 1.4 0 2 0.5 0.5 1.4 0.5 2 0l8.6-8.6C13.1 24.9 15.9 26 19 26c7.2 0 13-5.8 13-13S26.2 0 19 0zM19 24C12.9 24 8 19.1 8 13S12.9 2 19 2 30 6.9 30 13 25.1 24 19 24z"/></svg></a> <div style="display: none;" id="search-bar"> <input width="200" value="Search"/> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM