I have this code in a markdown cell in Jupyter Notebook which I want to use to give the user a hint if they are struggling to solve a particular problem. The following code manages to create and display a clickable button, but when I click it, nothing happens. Any suggestions on what I can do so that when the button is pressed, the text inside my div tag will be revealed?
<button onclick="toggle_visibility('hidden-content')">Click to reveal hint</button>
<div id="hidden-content" style="display:none">
You can use len(my_list % 2 == 0 to check if the length of the list is even
</div>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The code may work in jsFiddle, that doesn't mean it will work in the OP's framework or that the script tag will be parsed by the markdown to HTML transpiler, which is probably reHype. What is most likely happening is the button tag is allowed to be parse but script tags are not.
The only solution to this is to somehow load an external script that creates an event listener to handle the click of your button. I've never used your framework so I have no idea how to accomplish this. Also, you should get in the habit of using event listeners rather than invoking a function via the onclick property.
Here's an example:
const button = document.querySelector('.some-button');
button.addEventListener('click', (event) => {
console.log(button.dataset.content);
alert(button.dataset.content);
});
<button class="some-button" type="button" data-content="hidden-content">Click Me</button>
Related
i cant figure out how to stop the page reloading when i press the on click button... please if anyone can help tell me:)
(this is in html)
<button on click="My Function()">Try it</button>
<script>
function My Function() {
var x = document.get_Element_By_Id("mountain_bikes");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<script>
document.get_Element_)By_Id("mountain_bikes").style.display = "none";
i thought that this would show and hide when i toggle try it but it reloads the page every time i toggle please help!!
It looks like you've got a few errors going on here. Here's the answer:
// My Function() to myFunction()
function myFunction() {
// get_Element_By_Id to getElementById
var x = document.getElementById("mountain_bikes")
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
// get_Element_)By_Id to getElementById
document.getElementById("mountain_bikes").style.display = "none"
<!-- My Function() to myFunction() -->
<!-- on click to onclick —>
<!-- optionally add type="button" -->
<button type="button" onclick="myFunction()">Try it</button>
<!-- Added for demo -->
<div id="mountain_bikes">
My super cool mountain bikes.
</div>
As stated in a previous answer, it's just typos, but more than was mentioned. I'm sure you're still learning the basics, but this is something you should watch tutorials on, and maybe look at other people's code to get a better understanding of how JavaScript works. Your code works fine, without the typos, but this is something that's easily fixed by pasting the code into CodePen, or just running console.log() on your variables.
For future reference, you should also know about the preventDefault() function, that can be run on an event, like onClick. This is really only important in the case of forms, but if you run into other issues this may help. If you have a button in a form, but you don't want it to submit, make sure you include type="button" though. Here's how the preventDefault() function works:
// Setting constant variables since they never change.
// Using querySelector() for simplicity.
const article = document.querySelector('article'),
button = document.querySelector('button')
// Rather than using an onclick on the button in the HTML, I'm using an event listener to listen for the click event in JavaScript.
// This is the same thing as we had before, it just looks a little different.
button.addEventListener('click', (e) => { // Notice the e parameter. This is our event.
// This prevents the default behavior of our click event
e.preventDefault()
// This is the same as the if statement, just as a terny operator.
article.style.display === 'none'
?
article.style.display = 'block'
:
article.style.display = 'none'
})
// No need to set the style to none to start, since that's put in the HTML
<button type="submit">Click Me</button>
<!-- Here we set the display to none, so we don't have to do it in the JavaScript to start -->
<article style="display: none;">
<p>Without the preventDefault() function, the button would submit to the form—or at least try to, since there is no form—which would change the query in URL.</p>
<p>This could potentionally refresh the page, as is happening in your case.</p>
</article>
In your tag, the onclick needs to be one word, like this:
<button onclick="myFunction()">Try It</button>
Also, you shouldn't have spaces in your function names, I'm not a JS first guy, but I'm pretty sure no language allows for that (that I know of at least!)
I'm trying to make my webpage alert text when an element has been double-clicked using jQuery. Here's my JS:
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
And HTML:
<div class="dashboard-acrs-map-div" id="dashboard-acrs-map"></div>
Am I doing something wrong? Because the alert doesn't come up...
Note: It seems to be working UNLESS the element (#dashboard-acrs-map) is created using JS. How can I fix this?
That pretty much has to be your selected element not existing. It is possible that the script runs before the element is loaded. Place the script at the end of the body for example to make sure this is not the case.
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dashboard-acrs-map">
Element
</div>
Dynamic element creation example:
document.querySelector("button").onclick = () => {
var element = document.createElement("div");
element.id = "double-click-me"; // Who cares though?
element.textContent = "Double Click Me";
element.ondblclick = () => alert("Double!"); // Hook up double click here.
document.body.appendChild(element);
};
<button>Create Double-Clickable</button>
(Furthermore, i believe that jQuery should never be used.)
I am trying to optimize my "spoiler" bbcode on phpBB3.
Right now, I have a working solution, but the inline javascript is injected by phpBB every time the "spoiler" bbcode tag is used. I want to call a common function instead of adding it inline every time the bbcode is used.
Here is that working inline javascript:
<div class="spoiler">
<div class="spoiler-title">
<span onclick="if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = ''; this.parentNode.getElementsByTagName('a')[0].innerText = 'hide'; } else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none'; this.parentNode.getElementsByTagName('a')[0].innerText = 'show'; }">
<strong>{TEXT1}</strong> (show)
</span>
</div>
<div class="spoiler-text">
<div style="display: none;">
{TEXT2}
</div>
</div>
</div>
For ease of reading, the inline onclick function is repeated here:
if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') {
this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = '';
this.parentNode.getElementsByTagName('a')[0].innerText = 'hide';
} else {
this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none';
this.parentNode.getElementsByTagName('a')[0].innerText = 'show';
}
Clicking the anchor with the class of "spoiler-btn" has a preventDefaults on it, to prevent the click from taking you to the top of the page:
$(document).ready(function(){
$(".spoiler-btn").click(
function(e) {
e.preventDefault();
}
);
});
I was trying to replace the span onclick inline javascript with a function call that passes 'this' to an external javascript file. I couldn't seem to get that working, so I tried using jQuery to capture 'this' to traverse up the DOM to find the "div" contained within the "spoiler-text" div and manipulate the display:none. There can be multiple of these spoiler tags on the page, so I cannot give the div inside of the "spoiler-text" div an id.
Here I changed the onclick of the span to the external function:
onclick="spoilerToggle(this);"
I then have the following in my external file:
var spoilerToggle = function(param) {
if ($(this).parent('div').parent('div').hasClass('spoiler-text').css('style') == 'none') {
($(this).parent('div').parent('div').hasClass('spoiler-text').removeAttr('style'));
($(this).parent('div').$('a').text('hide'));
} else {
($(this).parent('div').parent('div').hasClass('spoiler-text').css('display', 'none'));
($(this).parent('div').$('a').text('show'));
}
}
The console then gives the following error:
bbcode.js:22 Uncaught TypeError: $(...).parent(...).parent(...).hasClass(...).css is not a function
Line 22 is the line with the "if" check.
jQuery is loaded on the site, and I've made sure to call my external javascript file right before the close of the body tag.
I feel like I've gone down the rabbit hole and cannot see the light. I'm sure this is much easier than I am making it out to be.
Any help is greatly appreciated. Thank you!
.hasClass() returns a boolean, so you can't chain other methods after it. That's why you get the error you quote.
I would implement it a different way though:
$(document).on("click", ".spoiler-title", function(e) {
e.preventDefault();
var container = $(this).closest(".spoiler");
container.find(".spoiler-btn").text(function(i, currentText) {
return currentText === "show" ? "hide" : "show"
});
container.find(".spoiler-text div").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="spoiler">
<div class="spoiler-title">
<span>
<strong>{TEXT1}</strong> (show)
</span>
</div>
<div class="spoiler-text">
<div style="display: none;">
{TEXT2}
</div>
</div>
</div>
The above uses a single, delegated click handler bound to the document to handle clicks on all spoiler elements on the page (you could instead bind it to a lower-level container element, at whatever the lowest level is that contains all the spoilers).
Within the handler, this will refer to the clicked element, so with DOM navigation methods such as .closest() and .find() you can go up to the containing div and then down to the elements you want to manipulate. .closest() is more flexible than trying to chain .parent().parent(), because it will automatically go up until it finds an element matching the specified selector, so if you later change your HTML structure the JS probably won't need to change.
If the .text() call looks confusing, what happens there is jQuery calls the function I passed to .text() as an argument, passing it the current value of the element's text and then whatever value is returned becomes the new text.
I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit.
The HTML is here
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
And here is the JavaScript Function
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
The CSS I used is given
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
If you want to check this application live here is the link
Please click on this link to see app in running form
If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.
When the app is first loaded, both the toggleFahrenheit and toggleCelsius divs have no style attribute. They are getting display rules from the CSS, true, but they have no style on themselves.
So think about what your code sees, then. fahrenheit.style.display is null because that block doesn't have the style attribute yet. Therefore, fahrenheit.style.display === 'none' evaluates to false. As a result, the else block is executed and you end up displaying Celsius. Unfortunately, this is the default block which is shown, so the first click doesn't do anything.
The second click works because after the code executes once, now both div blocks have a style attribute.
To fix this, you should either put default style attributes onto the div tags or flip the logic in the code so you check on the Celsius block first, since that's the default display.
Personally, I would use classes to toggle display behaviour instead.
function toggle() {
var fahrenheit = document.getElementById("fahrenheit");
var celsius = document.getElementById("celsius");
fahrenheit.classList.toggle('hide');
celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
And yes, I use -40 degrees in the example because I'm lazy and I happen to know this is the same temperature in both systems (:
It does not work because this if (fahrenheit.style.display === 'none') will return NULL as there is no inline style on the element. this method won't "look" at CSS, it only works for inline styles. You could try this:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
to check the CSS properties in pure JS or you could use JQuery which would solve it in one line of code.
This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:
function yourFunction() {
document.addEventListener("DOMContentLoaded", function(){
// you works start here
});
}
The simple solution is to use the EventListener .
I had the same problem with the onclick but when using :
const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {
//Your code here
});
It works on first click!
To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!