sorry if this is very simple but I am very new to programming.
The rest of my code is working fine, but I am trying to add a button which is hidden unless a certain element is added.
The code I have so far is this:
HTML:
<button onclick="setRace(); setSubRace()">Reroll Race</button>
<p id="race"></p>
<button id="rerollSubrace" onclick="setSubRace()">Reroll Subrace</button>
<p id="subrace"></p>
</div>
CSS:
#rerollSubrace {
display: none;
}
Javascript:
let showSubButton = document.getElementById("rerollSubrace").style.display = "inline";
...
function setSubRace() {
if (globalRace === "Aasimar") {
aasSubRace();
showSubButton;
The function continues for all options, and everything else in the setSubRace function works absolutely fine, the button just does not display.
Any advice would be great! Thank you in advance for all of your help!
The issue is with the way you declare your function showSubButton.
Thy the syntax ()=>{} instead.
let showSubButton = () => {document.getElementById("rerollSubrace").style.display = "inline";}
Here is a JsFiddle
Otherwise your statement is being always executed, setting the style to "inline".
Related
I'm trying to execute a function but only if a pop up is displayed or not. I've used Chrome Dev Tools to find the pop up element:
<div class="modal large popup is-visible" id="verifyIdentity" data-overlay-name="verify-identity">
When I close the pop-up, this changes to the below, with the words is-visible disappearing.
<div class="modal large popup" id="verifyIdentity" data-overlay-name="verify-identity">
I have tried the following:
if ($("#modal large popup").is(':visible')) { // do something }
if ($("verifyIdentity").hasClass('.modal large popup is-visible')) { // do something }
if ($(".parentClass").hasClass('.modal large popup is-visible')) { // do something }
None of these work and I am struggling to work out how to get my code to recognise that the pop-up is visible/not visible.
I'm new to JQuery and Javascript - can anyone help please?
Thanks
You are missing the # inside your selector.
This one should work properly
<button id="verifyBtn" onclick="verify()"> Verify </button>
function verify(){
if ($("#verifyIdentity").hasClass('is-visible')) { }
console.log("works");
}
Check with console.log("works"); if the function is executed properly.
Your has class approach is probably best here, however in the 'selector' for that example you're missing the actual 'ID' selector. Try:
if ($("#verifyIdentity").hasClass('is-visible')) { // do something }
You can also just target the is-visible, the rest we don't care about.
hasClassDetermine whether any of the matched elements are assigned the given
class.
I don't know much about jQuery so can offer no real help there but you ought to be able to do this using the IntersectionObserver API. If you click the button it will assign a class to the modal which I hope will emulate the modal becoming visible. The output element will be updated as a result because the IntersectionObserver callback has determined that it is visible.
const out=document.querySelector('output');
const iocallback=function( entries, observer ){
entries.forEach( e=>{
if( e.isIntersecting && e.intersectionRatio > 0 ) {
out.textContent='isVisible='+e.isVisible;
} else {
out.textContent='isVisible='+e.isVisible;
}
});
}
let modal=document.getElementById( 'verifyIdentity' );
let options={
root:null,
rootMargin:'0px',
threshold:1,
delay:100,
trackVisibility:true
};
let io=new IntersectionObserver( iocallback, options );
io.observe( modal );
document.querySelector('[type="button"]').onclick=(e)=>{
modal.classList.toggle('visible');
};
body,body *{box-sizing:border-box;margin:1rem;padding:1rem}
#verifyIdentity{ display:none; border:1px solid red; }
.visible{display:block!important;}
output{border:1px solid black;}
<div id='verifyIdentity'> #modal# </div>
<output></output>
<input type='button' value='Toggle visibility' />
For a project, I'm trying to highlight the logical fallacy of circular reasoning and have precious few lines of code later to be inserted into a separate webpage.
I am trying to create a simple process of clicking the displayed text to switch back and forth between the two questions. I've tried buttons and it only complicates and make no progress. Half a day gone, still banging my head on desk, as the phrase goes.
I read elsewhere that creating a var tracker facilitates, though I see it only for images, rather than displayed text. It feels like approaching my wits end, but I lack the time to walk away and try again.
This is my code thus far:
<!doctype html>
<head>
<script>
function change() {
var paragraph = document.getElementById("whytrust");
paragraph.innerHTML="I am trustworthy, but how can you be sure?";
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
You need some place to hold the old message so you can put it back again after you toggle the contents.
<!doctype html>
<head>
<script>
var newMsg = "I am trustworthy, but how can you be sure?";
function change() {
var paragraph = document.getElementById("whytrust");
var oldMsg = paragraph.innerHTML;
paragraph.innerHTML = newMsg;
newMsg = oldMsg;
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
This a quick and dirty implementation of what you want. I added a data-textindex attribute to the html element. There I stored an index for the currently shown text. In the javascript I check the current value, update data-textindex and replace it with new text.
function change() {
let paragraph = document.getElementById("whytrust");
let currentlyshown = paragraph.getAttribute('data-textindex');
if(currentlyshown == 0){
paragraph.innerText="I am trustworthy, but how can you be sure?";
paragraph.setAttribute('data-textindex', '1');
}else if(currentlyshown == 1){
paragraph.innerText="You can trust me, but how can you be sure?";
paragraph.setAttribute('data-textindex', '0');
}
}
<p id="whytrust" data-textindex="0" onclick="change();">You can trust me, but how can you be sure?</p>
On a sidenote: You can improve this code a lot. Like storing your text in a json-object. Or maybe using the ternary operator if you are 100% sure there will always be 2 choices. maybe give the function some arguments so you can apply it in a more general scenario.
Try tracking some sort of 'state' for your paragraph -- be it on/off, active/inactive...
Each time the change() function gets called, it doesn't remember what the paragraph was or was supposed to be. So, by setting a state of some sort (in my example a data-state attribute assigned to the paragraph element) the code can know how to behave.
function change() {
var paragraph = document.getElementById("whytrust");
var output = '';
// data-* can be anything, but handy for referencing things
var state = paragraph.getAttribute('data-state');
// check if data-state even exists
if( !state ){
// set it to the default/original state
paragraph.setAttribute('data-state', 'inactive');
state = 'inactive';
}
// toggle the state
// and assign the new text
if( state === 'inactive' ){
paragraph.setAttribute('data-state', 'active' );
output = "I am trustworthy, but how can you be sure?";
}else{
paragraph.setAttribute('data-state', 'inactive');
output = "You can trust me, but how can you be sure?";
}
paragraph.innerHTML = output;
}
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
Another option, without tracking state could be hiding and showing the paragraph you want displayed. You don't really need to track state or save the alternating text...
// get the elements from the DOM that you want to hide/show
// you can get tricky and add alternative ways to track
// the paragraph elements, but this works nice for a demo
const whytrust = document.getElementById('whytrust'),
answer = document.getElementById('whytrust-answer');
function change( element ){
// the element parameter being passed is the paragraph tag
// that is present/visible
if( element.id === 'whytrust' ){
answer.className = ''; // clear the .hide class
whytrust.className = 'hide'; // add the .hide class
}else{
whytrust.className = ''; // clear the .hide class
answer.className = 'hide'; // add the .hide class
}
}
.hide{ display: none; }
<p id="whytrust" onclick="change(this);">I am trustworthy, but how can you be sure?"</p>
<p id="whytrust-answer" class="hide" onclick="change(this);">You can trust me, but how can you be sure?</p>
What I like about this solution is that it keeps the content in the HTML and the JavaScript just worries about what to hide/show.
I want to click on a link to change the source of an image. Here's what I have come up with so far :
HTML :
click
<div id = "bulb">
<center><img src = "C:\Users\hp\Desktop\on.gif" style = "width:180px;height:270px;position:relative;top:25px;border:2px solid black;"></center>
</div>
JS :
function changesrc() {
var work = document.getElementById('bulb');
if (work.src.match(C:\Users\hp\Desktop\on)) {
work.src = "C:\Users\hp\Desktop\off.gif";
}
else {
work.src = "C:\Users\hp\Desktop\on.gif";
}
}
I am a beginner in javascript, so please help me. According to me, on clicking the a (with text click) the function change src gets executed.that func. has a variable work. the work calls the element by id = bulb. If that variable's(work's) src matches that of the image on my desktop(with the bulb on
) then it gets changed to off else it changes to on(as if it isn't on that means it's off and so we change that).
I took help from w3schools. I looked up similar questions. I even changed work.src to bulb.src . Still cant find my mistake. Please help and tell me what's causing this!!! No jQuery please as I don't know it yet.
document.getElementById('bulb') is not an image. In your code you are changing the "src" of the <div>.
Change the id to the image, like:
click
<div style="text-align:center;"">
<img id="bulb" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-logo-med.png?v=d9b0b6647f17" style="width:180px;height:270px;position:relative;top:25px;border:2px solid black;">
</div>
And Javascript:
function changesrc(){
var work = document.getElementById('bulb');
if(work.src.indexOf('se/se-')){
work.src = 'http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo-med.png?v=6f86a5fa447f';
}
else{
work.src = 'http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-logo-med.png?v=d9b0b6647f17';
}
}
Update:
"return" corrected: onclick="changesrc(); return false;".
if (work.src.match(C:\Users\hp\Desktop\on)) {
This should be matching a string?
if (work.src.match('C:\Users\hp\Desktop\on')) {
You're using the match function which expects a RegExp as a parameter. Actually I think that in your case you could just compare the strings:
if (work.src === 'C:\Users\hp\Desktop\on') {
Hey guys I have searched for many answers and none of them seem to be working so I am going to put my code here and hopefully you can help me figure this out.
I am going to have two buttons. The first button (show_Chappie) is going to show the hidden contents and another button (hide_Chappie) and hides it self when clicked.
The second button (hide_chappie) is going to hide the contents and bring back the first button (show_chappie). The hide_chappie button itself would also be hidden.
The information div is already hidden from the start. I did this on the CSS using the display:none;
Here's my HTML code so far:
<button class ="show_chappie" onclick="showInfo()">Show More</button>
<div class="info">Info here.</div>
<button class ="hide_chappie" onclick="hideInfo()">Show Less</button>
Here's my JavaScript code so far:
function showInfo(){
document.getElementById('chappie_info').style.display = "inline-block";
document.getElementById('show_chappie').style.display = "none";
document.getElementById('hide_chappie').style.display = "inline-block";
}
I haven't written the code for the hide_chappie button because I wanted to see this working first.
So where have I gone wrong here? Thanks for the help in advance.
You are trying to get the elements by id while they have a class, you should change the elements class to id like this:
<button id="show_chappie" onclick="showInfo()">Show More</button>
<div id="info">Info here.</div>
<button id="hide_chappie" onclick="hideInfo()">Show Less</button>
you should change your code to:
<button id ="show_chappie" onclick="showInfo()" >Show More</button>
<div class="info">Info here.</div>
<button id= "hide_chappie" onclick="showInfo()">Show Less</button>
if you want to use class here,you should change your Javascript Code to
function showInfo(){
document.getElementByClass('chappie_info')[0].style.display = "inline-block";
document.getElementByClass('show_chappie')[0].style.display = "none";
document.getElementByClass('hide_chappie')[0].style.display = "inline-block";
}
because function getElementsByClass returns a collection,so you should add [] to find out the result you want!
It's kind of annoying to turn all id's into classes, you can use:
function showInfo(){
document.getElementsByClassName('chappie_info').style.display = "inline-block";
document.getElementsByClassName('show_chappie').style.display = "none";
document.getElementsByClassName('hide_chappie').style.display = "inline-block";
}
This is supported by practically every browser these days so I wouldn't worry about that. If that is still an issue an you need to support ancient browsers, use this:
document.getElementsByClassName = function (a) {
var b = document.getElementsByTagName('*'), i, c=[];
for (i = 0; i < b.length; i += 1) { b[i].getAttribute('class')===a&&c.push(b[i]); }
return c;
};
im trying to make a switch wich will change two images. I once solved ths, but then i lost some important files, the one containing the final script being one.
The idea is that when the button is clicked, it will change image 1 for image 2 and will change its own image from on to off. Then, when clicked again it will change image 2 for image 1 and its own image from off to on.
I been trying something like this, buts not working, not sure why. I think i got the wrong declaration for the if which determines if the switch is on or off, but again not sure.
Before you read the code and realize its poorly done, consider i dont know a thing about javascript, i only have a vague idea of how it works.
<script type="text/javascript">
var vswitch = false;
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
function change(){
if (vswitch == true){
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
} else {
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
}
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif">
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif" onclick='change();'>
</div>
</script>
Thank you
/////////////////////EDIT///////////////////////////
Thanks a lot.
Having those two functions there was a result of the previous code, i dont understand how i didnt realize it until you pointed out, heh. (Sleepyness maybe?)
#renuka, that code worked perfectly. I only changed the calling div, from the div "toggle" you created to the div "container" since the button has to switch the images itself, but other than that was sweet. Thanks.
Thanks for the help!
There are a couple of problems here :)
First:
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif")
^ this assigns a variable
You want to change = to === so that a comparison is done
Second, you're creating functions changelamp and changeSwitch but you're never actually calling them. I think you want to get rid of the function declarations completely:
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
} else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
Finally, there are some minor syntax errors such as missing semi-colons
vswitch = true; // <- like this
Please check the updated code below:
<script type="text/javascript">
function change(){
var vswitch = false;
if (document.getElementById("switchh").src == "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
</script>
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif"/>
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif"/>
</div>
<div id="toggle">
<input type="button" value="On/Off" onclick='change();'/>
</div>
The '=' assigns the value to the "src" of the image. Replace it with '==' for comparison.
Additionally from what jasonscript says, you are never switching the vswitch variable to the opposite state, so you'd need to add
vswitch = !vswitch;
after the if in the change() function, that way, the next time you click in the switch, it takes the "other" path through the if
Another point is that if you have the code layout as you have it in your post (script first and then the HTML code) the first if will actually not find the #switchh img, so you need to either move the if inside the change() function or move your script after the HTML
Major problem is that you are unnecessarily creating functions inside script which are never called.
No need for
changelamp() and changeSwitch()
You can directly post the code after the if condition check.
<script> tags should be closed. = assigns and === does comparison, and you need to change the value of vswitch.
Here is a fiddle that accomplishes what you're after with some random images