Reputation: 93
I'm creating a drop-down element with only one option below. I stuck when I need to show/hide this option.
HTML:
<div id="div1">
<i class="fa fa-plus-square" title="Some title" type="button">
<span id="spanId" title="Some other title">Some text</span>
</div>
<i>
-is the image drop-down button.
CSS:
#div1 {
cursor: pointer;
/*styles, which are not related to the issue*/
}
#spanId {
display: none;
/*some other styles*/
}
#spanId :hover {
background: #e7edf4;
}
So, the span is hidden. I can show it, but after that it is remaining visible for ever and I`m not able to hide it.
JS/JQuery:
let visible = false
const toggleButton = $('#div1')
const dropDownBtn = $('#spanId')
const someOtherButton = $('#someId')
toggleButton.click(() => {
dropDownBtn.css("display", "block")
visible = true
})
if(visible == true){
$(document).click(() => {
dropDownBtn.css("display", "none")
visible = false
})
}
dropDownBtn.click(() => {
someOtherButton.click()
})
Also I tried to do it with <select>
, bu did not succeed. Also try show() & hide()
methods of jQuery. I really can`t realize where am I wrong.
Upvotes: 0
Views: 95
Reputation: 56744
Simply toggle a class:
div1.addEventListener('click', () => spanId.classList.toggle('visible'))
document.addEventListener('click', (e) => {
if (!div1.contains(e.target)) spanId.classList.remove('visible')
})
#spanId { display: none; }
#spanId.visible { display: block; }
<div id="div1">
<i class="fa fa-plus-square" title="Some title">ICON HERE</i>
<span id="spanId" title="Some other title">Some text</span>
</div>
Also your code had errors. The <i>
was not closed properly, and i
does not have a type
attribute. The Javascript logical error you made was already mentioned in your comments.
Or, if you insist on jQuery:
$(div1).on('click', () => $(spanId).toggleClass('visible'))
#spanId {
display: none;
}
#spanId.visible {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<i class="fa fa-plus-square" title="Some title">ICON HERE</i>
<span id="spanId" title="Some other title">Some text</span>
</div>
Upvotes: 1