I have a clickable span element that is supposed to call a javascript function that toggles a dropdown. This is an amalgum of two w3schools examples linked here.
onclick with span element
clickable dropdowns with w3.css
My code is below, the HTML and JS are inline in the same HTML document. The CSS can be ignored, it is just renamed w3.css stuff (w3- to mxa-).
HTML
<div class="mxa-dropdown-click">
<span onclick="menu_click("page-menu")">
<span class="mxa-xlarge">☰</span>
</span>
<div id="page-menu"
class="mxa-dropdown-content mxa-bar-block mxa-border"
>
<a href="/entity/show/42" class="mxa-bar-item">
Show Entity
</a>
<a href="/record/add/prompt/42" class="mxa-bar-item">
Add Record
</a>
</div>
</div>
JS
function menu_click(menu_id) {
window.alert('i got to here');
var menu = document.getElementById(menu_id);
if (menu.className.indexOf("mxa-show") == -1) {
menu.className += "mxa-show";
} else {
menu.className = menu.className.replace("mxa-show", "");
}
}
I have edited an example from the w3schools site that to me looks essentially identical to my code but which does work.
<!DOCTYPE html>
<html>
<body>
<span id="demo" onclick="myFunction('demo')">Click me to change my text color.</span>
<script>
function myFunction(arg) {
window.alert('i got to here');
document.getElementById(arg).style.color = "blue";
}
</script>
</body>
</html>
I never 'get to here' in my code. What could I be doing wrong?
You are forming the onclick attribute with invalid syntax, change the inner double quotes to single quotes.
Change
<span onclick="menu_click("page-menu")">
To
<span onclick="menu_click('page-menu')">
OR: With double quotes inside the single quotes
<span onclick='menu_click("page-menu")'>
function menu_click(menu_id) {
window.alert('i got to here');
var menu = document.getElementById(menu_id);
if (menu.className.indexOf("mxa-show") == -1) {
menu.className += "mxa-show";
} else {
menu.className = menu.className.replace("mxa-show", "");
}
}
<div class="mxa-dropdown-click">
<span onclick="menu_click('page-menu')">
<span class="mxa-xlarge">☰</span>
</span>
<div id="page-menu"
class="mxa-dropdown-content mxa-bar-block mxa-border">
<a href="/entity/show/42" class="mxa-bar-item">
Show Entity
</a>
<a href="/record/add/prompt/42" class="mxa-bar-item">
Add Record
</a>
</div>
</div>
All are same except onclick quote .check your quotes on onclick call
onclick="menu_click('page-menu')"
function menu_click(menu_id) {
window.alert('i got to here');
var menu = document.getElementById(menu_id);
if (menu.className.indexOf("mxa-show") == -1) {
menu.className += "mxa-show";
} else {
menu.className = menu.className.replace("mxa-show", "");
}
}
<div class="mxa-dropdown-click">
<span onclick="menu_click('page-menu')">
<span class="mxa-xlarge">☰</span>
</span>
<div id="page-menu" class="mxa-dropdown-content mxa-bar-block mxa-border">
<a href="/entity/show/42" class="mxa-bar-item">
Show Entity
</a>
<a href="/record/add/prompt/42" class="mxa-bar-item">
Add Record
</a>
</div>
</div>
I noticed that you are calling function error. Just replace these line of code.
Hope it will help you.
<span onclick="menu_click('page-menu')">
<span class="mxa-xlarge">☰</span>
</span>
Related
I have a JS function that works with a button; basically, it's supposed to show the HTML code after clicking the button. However, for some reason, when I load the page, the HTML is visible before clicking the button; clicking the button once makes the code disappear, and then clicking it again makes the code re-appear. It seems like the function is doing the opposite of what I want it to do, but I have no idea why it's doing this: comparing my code to other code that does what I want it to do, I don't see any visible differences.
Here is the script:
<script>
function showTweet() {
var x = document.getElementById("tw-block-parent");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Here is the HTML that the script is supposed to make visible:
<div id="tw-block-parent">
<div class="timeline-TweetList-tweet">
<div class="timeline-Tweet">
<div class="timeline-Tweet-brand">
<div class="Icon Icon--twitter"></div>
</div>
<div class="timeline-Tweet-author">
<div class="TweetAuthor"><a class="TweetAuthor-link" href="#channel"> </a><span class="TweetAuthor-avatar">
<div class="Avatar"> </div></span><span class="TweetAuthor-name">TwitterDev</span><span class="Icon Icon--verified"> </span><span class="TweetAuthor-screenName">#TwitterDev</span></div>
</div>
<!--This is where the tweet text goes-->
<div id="timeline-Tweet-text_1"></div>
<div class="timeline-Tweet-metadata"><span class="timeline-Tweet-timestamp">9h</span></div>
<ul class="timeline-Tweet-actions">
<li class="timeline-Tweet-action"><a class="Icon Icon--heart" href="#"></a></li>
<li class="timeline-Tweet-action"><a class="Icon Icon--share" href="#"></a></li>
</ul>
</div>
</div>
</div>
And finally here is the HTML button:
<input type="submit" onclick="onClick(); showTweet();" id="submit-button" class="instructions" value="try me!">
The 'OnClick();' function works fine as far as I know, but just in case I'll post it here too.
<script>
//This function allows different inputs to display different text blocks
function onClick() {
if (document.getElementById("user_input").value === "I hate the EU!")
{
antiEuropeExample();
}
else if (document.getElementById("user_input").value === "I hate traffic!")
{
antiTrafficExample();
}
else if (document.getElementById("user_input").value === "I hate Trump!")
{
antiTrumpExample();
}
else if (document.getElementById("user_input").value === "I hate Facebook!")
{
antiFacebookExample();
}
else
{
alert("Wrong input buddy!");
}
}
</script>
I apologise for the amount of code I've posted here, I hope the question is understandable and that you guys can help! Thank you so much :)
All <div> elements have default styling display:block;, if you want to change the initial behavior of a particular element you have to add styling to it.
in your case i would advice changing this:
<div id="tw-block-parent">
to
<div id="tw-block-parent" style="display:none;">
This would make the div invisible at the start.
Newish to javascript, but I do't know why the below is not working. I am trying to use javascript to make a link become active after a button has become clicked.
The user clicks a button that updates the HTML, changes the class and adds a html link. The code works the first time -- the HTML is updated correctly. However if the user decides to un-click the button nothing happens.
Javascript:
function agree() {
let agreement = document.getElementById("agreement");
let agree = document.getElementById("agree");
agree.onclick = () => {
if (agree.value === true) {
agreement.innerHTML = `
<button id="agree" class="agree--no" value="false"></button>I agree
<div class="btn--no-schedule">
<a href="#" > No SCHEDULE </a>
</div> `
} else {
agreement.innerHTML = `
<button id="agree" class="agree--checked" value="true"><i class="fas fa-lg fa-check-square"></i></button>I agree
<div class="btn--agree-schedule">
<a href="http://google.com" > yes SCHEDULE </a>
</div> `
}
}
};
HTML
<div id="agreement">
<button id="agree" class="agree--no" value="false"></button>I agree
<div class="btn--no-schedule">
<a href="#" > SCHEDULE </a>
</div>
</div>
I also tried
<button onclick=“agree();” id="agree" class="agree--no" value="false"></button>
but get a type error agree() is not a function.
Any help would be appreciated
There are two errors here.
First, the click event is lost when you reset the agreement's innerHTML, second, agree.value is a string, and thus will never be "=== true".
There are multiple ways of fixing it. One way is changing the innerHTML part so the event isn't lost. Also, changing the condition to === 'true'
Like so:
HTML:
<div id="agreement">
<button id="agree" class="agree--no" value="false"></button>I agree
<div id="schedule-btn" class="btn--no-schedule">
<a href="#" > SCHEDULE </a>
</div>
</div>
JS:
function agree() {
const agreeBtn = document.getElementById("agree");
const scheduleBtn = document.getElementById("schedule-btn");
agreeBtn.onclick = () => {
if (agreeBtn.value === "true") {
agreeBtn.value = false;
scheduleBtn.innerHTML = `
<div class="btn--no-schedule">
<a href="#" > No SCHEDULE </a>
</div>
`;
} else {
agreeBtn.value = true;
scheduleBtn.innerHTML = `
<div class="btn--agree-schedule">
<a href="http://google.com" > yes SCHEDULE </a>
</div>
`;
}
};
}
Edit: I tried to alter your code as little as possible
Try this code:
function ChangeContent(checkbox) {
var el = document.getElementsByClassName("schedule-agreement")[0];
(checkbox.checked) ? el.innerText = "No SCHEDULE": el.innerText = "Yes SCHEDULE"
}
<div id="agreement">
<input type="checkbox" onchange="ChangeContent(this)"> I agree
<div>
SCHEDULE
</div>
</div>
Explanation:
First of all, add a change event listener to the input checkbox. Then, whenever it is run, check if it is checked. If it is, change the link's innerText to "No SCHEDULE", otherwise, change it to "Yes SCHEDULE".
If you need to use a button, then I would recommend adding a click event listener (or an onclick inline event listener), and changing the link innerText ONLY - not the whole HTML.
In that case, here's a separate demo:
var isChecked = false
function ChangeContent() {
isChecked = !(isChecked)
if (isChecked) {
document.getElementsByClassName("agree")[0].innerText = "✔️ I agree"
document.getElementsByClassName("schedule-agreement")[0].innerText = "No SCHEDULE"
} else {
document.getElementsByClassName("agree")[0].innerText = "❌ I agree"
document.getElementsByClassName("schedule-agreement")[0].innerText = "Yes SCHEDULE"
}
}
<div id="agreement">
<button class="agree" onclick="ChangeContent()">I agree</button>
<div class="btn--no-schedule">
SCHEDULE
</div>
</div>
I need some help with my code, I have got a problem with fetch the text while ignore the class menu-list-count as it will display the value next to the text.
When I try this:
var mailfolder = $(this).not('[class="menu-list-count"]').text();
The return output will be:
test1 2
It should be:
test1
Here is the html:
<a id="iJ" class="menu-list-item mailfolder" href="#test1" target="_top" title="test1" tabindex="-1" draggable="false">
<div class="qj">
<i style="float: left;" class="folder_icon"></i>
</div>
<span style="margin-left: 7px;">test1 <span class="menu-list-count">2</span></span>
</a>
Here is the code:
$(document).on('click', '.mailfolder', function(e) {
e.preventDefault();
var mailfolder = $(this).not('[class="menu-list-count"]').text();
alert(mailfolder);
});
I have tried this:
var mailfolder = $(this).find('span:not(.menu-list-count)').text();
It doesn't work when I try it as i still getting test1 2 so I dont really know what to do,
Can you please show me an example how I can get the span text while ignoring the class menu-list-count?
Because you have a span in a span, in order to select the right one you need to change this line:
$(this).not('[class="menu-list-count"]')
to:
$(this).find('span:not([class="menu-list-count"])')
In order to get only the text belonging to the upper span you can combine .contents() with .filter():
$(this).find('span:not([class="menu-list-count"])').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE; // get only text nodes
}).text()
The snippet:
$(document).on('click', '.mailfolder', function(e) {
e.preventDefault();
var mailfolder = $(this).find('span:not([class="menu-list-count"])').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).text();
console.log(mailfolder);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="iJ" class="menu-list-item mailfolder" href="#test1" target="_top" title="test1" tabindex="-1" draggable="false">
<div class="qj">
<i style="float: left;" class="folder_icon"></i>
</div>
<span style="margin-left: 7px;">test1 <span class="menu-list-count">2</span></span>
</a>
I'm not sure with JQuery, but with plain JS you can use childNodes to filter everything that is not a textNode and then concatenate the result.
I've wrote a small JSFiddle to show how it works: https://jsfiddle.net/sandro_paganotti/4873muzp/6/
HTML
<div>
Hello
<b>Some Text</b>
</div>
JS:
const nodes = Array.from(document.querySelector('div').childNodes);
const text = nodes.map(t =>
t.nodeType == Node.TEXT_NODE
? t.textContent
: ''
);
console.log(text.join(''));
What I want is to call the showPopup('text goes here'); function and the below block of code to be shown with my text in it.
How can I achieve this?
function showPopup(data) {
}
<a class="fragment" href="#">
<span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
<div class="content">
// I WANT TO PUT MY TEXT HERE
</div>
</a>
JSFiddle example: http://jsfiddle.net/tb5musm6/
function showPopup(data) {
var elem = document.getElementsByClassName('content');
elem[0].innerHTML = data;
}
showPopup('asdf');
document.getElementsByClassName will return an array of elements with the given classname
innerHTML variable holds all content between tags
Add an id to you div so you can find it easier.
Then, use innerHTML to modify the content of the div.
<a class="fragment" href="#">
<span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
<div class="content" id="content">
// I WANT TO PUT MY TEXT HERE
</div>
</a>
<script>
function showPopup(data) {
document.getElementById('content').innerHTML(data);
}
showPopup('my text');
</script>
I have serval link buttons in order to show a div below it.
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
I want to clink one linkbutton and only show the div element below it. but my js code:
function showComment(){
var isshow=$(this).attr('isshow');
if(isshow=="0"){
this.$(".comment").show();
$(this).attr('isshow',"1");
}
else{
this.$(".comment").hide();
$(this).attr("isshow","0");
}
}
this show all div. and when i use $(this).siblings() or $(this).next(), i got null, i don't know why that not work.
What can i do?
this is not pointing to the element if you run it in an inline event. Try the following:
onclick="showComment(this)"
And:
function showComment(el) {
var isshow=$(el).attr('isshow');
if(isshow=="0"){
$(el).next(".comment").show();
$(el).attr('isshow',"1");
}
else{
$(el).next(".comment").hide();
$(el).attr("isshow","0");
}
}
Or if you use jQuery's click, you can use this to point to the element:
$('.btnComment').click(function(event) {
var isshow=$(this).attr('isshow');
if(isshow=="0"){
$(this).next(".comment").show();
$(this).attr('isshow',"1");
}
else{
$(this).next(".comment").hide();
$(this).attr("isshow","0");
}
});
You should wrap your <a> and <div> inside another <div> to create a more maintainable code. Like this:
<div class="commentContainer">
<a class="btnComment" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<div>
This parent div serves as the context for your tags. In the future, if you change the position, move <a> after <div>, your code still works fine. And it's even possible for you to to styling as a group just by assigning a class to the container.
Your jquery, here I use jquery event handler instead.
$(".btnComment").click(function () {
var isshow = $(this).attr('isshow');
var parent = $(this).closest(".commentContainer");
if (isshow == "0") {
parent.find(".comment").show();
$(this).attr('isshow', "1");
} else {
parent.find(".comment").hide();
$(this).attr("isshow", "0");
}
}
If you use .next(), it means your code is coupled to the current html.
css
.hide{visibility:hidden;}
.show{visibility:visible;}
jquery
$('.btnComment').click(function(){
$('.btnComment + div').removeClass('show').addClass('hide');
$(this).next().removeClass('hide').addClass('show'); });
html
<a class="btnComment" href="javascript:;"
sshow='0'>click1</a> < div
class="hide">sandy1</div> <a class="btnComment"
href="javascript:;" isshow='0'>click2</a> <div
class="hide">sandy2</div> <a class="btnComment"
href="javascript:;" isshow='0'>click3</a> <div
class="hide">sandy3</div>
On every click of anchor tag respective div will be shown and others will be hidden.
Hope this will help you.