I am trying to add a javascript class show with dropdown-content, but it is not adding there infact while console logs are working perfectly fine upto the last scope of the javascript script tag. Can anyone help me out from this?
The text with the id is basically coming from django database which is unique.
<div >
<a href="#" onclick="get()" id="{{course.course_id}}" ><i ></i></a>
<div >
<span><i ></i>Save</span>
<span><i ></i>Not Interested</span>
<span><i ></i>Report</span>
</div>
</div>
<script>
function get() {
const focused = document.activeElement.getAttribute("id");
console.log(focused);
menu(focused);
}
function menu(focused) {
const path = '#' focused ' .dropdown-content';
console.log(path);
$(path).toggleClass("show");
}
</script>
.eps_dots .show{
display: block !important;
}
CodePudding user response:
Given that you're using jQuery, you should not be retrieving the id
attribute of the clicked element as a string to manually concatenate a selector together.
In addition, you should be using unobtrusive event handlers to bind your events, not inline onclick
attributes. This would allow you to get a reference to the clicked element from the event that's passed to the handler as an argument. From there you can traverse the DOM to find the .dropdown-content
to toggle the relevant class.
jQuery($ => {
$('.eps_dots > a').on('click', e => {
e.preventDefault();
$(e.currentTarget).closest('.eps_dots').find('.dropdown-content').toggleClass('show');
});
});
.dropdown-content {
display: none;
}
.eps_dots .show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div >
<a href="#" >
Click here...
<i ></i>
</a>
<div >
<span><i ></i>Save</span>
<span><i ></i>Not Interested</span>
<span><i ></i>Report</span>
</div>
</div>
CodePudding user response:
In the "menu" function you have used the given path does not exist because the id would not be parent of the dropdown-content, but instead it would be it's sibling so it would never work.
For your code to work the .dropdown-content should be wrapped inside the anchor tag like this
<a href="#" onclick="get()" id="{{course.course_id}}" ><i ></i>
<div >
<span><i ></i>Save</span>
<span><i ></i>Not Interested</span>
<span><i ></i>Report</span>
</div>
</a>
But as this isn't the case you should try using the sibling format
let current = document.querySelector('#' focused);
let nextSibling = current.nextElementSibling;
Here the nextSibling would be your dropdown-content element