Hiding / displaying content in javascript - javascript

I am a very new web developer. I'm doin fine with HTML and CSS and im trying to learn javascript. Im very new 1 month ago I never coded a single line, and I've made 2 or 3 websites already but none are JS capable.
I know I can do this in jquery and have already, but I want to Understand it and I want to be able to do it in vanilla javascript.
So here it is . I am making a simple game for practice, all it does is ask questions and change elements from display = none to display = block based on a click event to two big YES or NO buttons.
So.... this first code targeting yes_button works fine. The instructions Hide and the first questiong (Q1) appears.
the No button does not work, and I cannot figure out why, it is essentially the same code targeting a different element.
Things I checked :
the element id/selectors are correct
camelCase is good,
no unclosed braces,
semi colons are good,
is the mistake in the logic somewhere?
window.onload = function() {
yes_button.onclick= function() {
document.getElementById("instructions").style.display="none";
document.getElementById("q1").style.display="block";
};
no_button.onClick=function() {
document.getElementById("instructions").style.display="none";
document.getElementById("nointro").style.display="block";
};
};

You can remove the window.onload function call. You can place your JavaScript imports just before the closing tag so the dom is ready before you attempt to click on the button.
Your JavaScript Events should look like this:
document.getElementById("yes_button").onclick = function(){
document.getElementById("instructions").style.display= "none";
document.getElementById("q1").style.display = "block";
};
document.getElementById("no_button").onclick = function(){
document.getElementById("instructions").style.display="none";
document.getElementById("nointro").style.display="block";
};

Related

Javascript help for a Chrome extension

First of all, I am not a programmer. I do not know Javascript at all. I'm trying to create a Chrome extension that modifies my browser tab's title, by taking a specific string on a webpage. I know how to create Chrome extensions (just barely) and I just need to modify the Javascript to do what I want (which I do not know how).
I found the following script online and am trying to modify it but can't figure out how to get it working. Here is the script:
https://pastebin.com/dY1LSdjT
// Fire this event any time the mouse is moving. Sucks for performance, but it's a better experience
document.addEventListener("mousemove", function() {
// This will get us the banner
let bannerTextElements = document.getElementsByClassName("dijitReset dijitInputField dijitInputContainer");
console.log(bannerTextElements);
console.log(bannerTextElements[0]);
if (bannerTextElements[0]) {
console.log("ok!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(bannerTextElements[0].innerHTML);
// This will get us the text
let bannerTextLine = bannerTextElements[0].getElementsByClassName("dijitReset dijitInputInner");
console.log(bannerTextLine);
document.title = bannerTextLine[0].innerHTML
}
}, false);
And here's the website viewed in developer mode. I would like to get the text "blahhhh" and use that for the title of my browser tab.
Below is a different webpage and the difference here is that the "div class" names will change. The numbers in those class will change to different numbers, but the structure and the overall name remains the same. For example, "ms-Button-label label-549" may change to "ms-Button-label label-640". This happens whenever you refresh the page. I found that the "viewport" id name doesn't change though, so I think if we can use that as a reference and then just look at the nested div classes and reference them and extract the value (in this case Crystal Mountain).
Fixing your code
You got like 95% of everything you need.
The one thing you are missing right now is that the fact that an input element does not posses an "innerHTML" (That is why it isn't closed like this: <input>renderedText</input>). Instead you want to check for it's value:
document.title = bannerTextLine[0].value;
Some Improvements:
Search by ID
You have a well defined input which can be more easily obtained by looking it up using the id:
let bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
End result:
const bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
bannerTextLine.addEventListener("blur", function() {
if (bannerTextLine != null) {
document.title = bannerTextLine.value;
}
});
This is the entire JS code. Note that I changed the event to blur which activates when the form is left, this should be optimal for your case.

using javascript to change text on a window resize

the problem at the moment is that when the windows get resized some text gets cut off. I've seen websites where when the window resizes the text changes to an abbreviation or another word. People were telling me that this is angular js but since then I've tried finding something related to it and couldn't. So i'm back to using good old javascript and here is my code
http://jsfiddle.net/duy8zvmm/71/
The problem is that i don't want this first
var myspan = document.getElementById('players-signedup');
if (myspan.innerText) {
myspan.innerText = "Players";
}
else
if (myspan.textContent) {
myspan.textContent = "Players";
}
and can't understand why i need it there, because the resize if statements i have do work, i have tested using background colors on a div. So i can't understand why they aren't working here

JQuery Toggle Divs Based On Index not retoggle when clicked twice

and thank you for reading this question. Let me preface this by saying that I am not a programmer and only have tried to learn javascript to make my own websites look and function the way I want.
I have a page with several hidden divs. I'm using elements with the same class and different targets to trigger this Jquery
jQuery(function () {
jQuery('.nav').click(function () {
var index = $(this).index(),
newTarget = jQuery('.targetDiv').eq(index);
jQuery('.targetDiv').not(newTarget).slideUp('fast')
newTarget.delay('fast').slideToggle('fast')
return false;
})
});
So my ".targetDiv"s look like this:
<div class=".targetDiv" style="display:none">div1</div>
<div class=".targetDiv" style="display:none">div2</div>
<div class=".targetDiv" style="display:none">div3</div>
And the "navigation" would look something like this
link1
link2
link3
This is not my code, and I got it from here: http://forum.jquery.com/topic/slidetoggle-multiple-divs-31-5-2013
It works exactly as it is supposed to and I have no complaints about that. When you click on a link, the corresponding div toggles, but when you click the same div again right afterwards, it toggles again and slides up (which is how the code is written). I want to stop that from happening, and since I am new to Javascript and Jquery I can't figure out how to do it. My non programmer mind assumes that there should be some kind of if else clause, where you would say:
if .targetDiv is :visible, then do not toggle newTarget. However when I tried to do that, it did not work.
if($(".targetDiv").is(":hidden")) { jQuery(function () {
jQuery('.nav').click(function () {
var index = $(this).index(),
newTarget = jQuery('.targetDiv').eq(index);
jQuery('.targetDiv').not(newTarget).slideUp('fast')
newTarget.delay('fast').slideToggle('fast')
return false;
})
});}
else {alert("already open")}
I don't know how else I should handle this, but it must be possible and I am probably just thinking of how to achieve what I want in entirely the wrong way. I understand very little about javascript, but I am not asking for someone to write this for me, I'd rather have someone tell me what it is that I am doing that is incorrect, then explain what it is I should be trying to do. Then I can use google to search for the way to achieve that.
Again, thank you for taking the time to read this and hopefully I've been detailed enough for some answers.
You just need to wrap the two 'slide' lines in the if statement, like so:
if (!newTarget.is(':visible'))
{
jQuery('.targetDiv').not(newTarget).slideUp('fast');
newTarget.delay('fast').slideToggle('fast');
}
You may also want to fix a few issues with the html, e.g. take the periods out of your class names. When querying for DOM elements, the "." means, "Find the things that have a class called _[whatever follows the dot]". Don't put dots in the classes themselves.
You may also want to take out the href attributes of the <a> tags. They aren't necessary.
Here's a working JSFiddle. Cheers!

jQuery + Modernizer - Do not display a div if javascript is disabled? (See Code)

I am trying to enhance the menu of my website a bit by making use of the jQuery accordion plugin:
http://jqueryui.com/accordion/
This works perfectly fine and i think that it is a great plugin to make use of... However, i have noticed that it requires a specific layout in order to achieve these results:
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>
ETC...
</p>
</div>
NB: repeated for every result
</div>
Now this is a bit of a problem in that when javascript is disabled, the entire output of this menu is displayed (all categories and containing information).
This is simply too much information to be output all at once and this is the reason that it has been broken up with PHP in the first place. In essence it would look like this:
// No category selected
* Fruits
* Vegetables
// Category selected
o Fruits
- Apples
- Oranges
* Vegetables
// Javascript Disabled
o Fruits
- Apples
- Oranges
* Vegetables
- Potatoes
- Onions
So what i would like to do, is provide an alternate means of navigation for users that have disabled javascript (the old menu that is fully functional and works regardless).
I currently make use of a few options in modernizer:
http://modernizr.com/
To increase browser support on some CSS properties i have used. I am aware that it can be used to detect if javascript is enabled by appending a class "js" to the body tag.
So with that, i decided to try and wrap the old menu within a containing div, and the new menu within a containing div. My idea is that i can then these divs with display: none;.
Before i carry on, i am really just guessing here so if i am going about this the wrong way... I would appreciate it if someone could point me in the right direction. With that out of the way, i found an article on stackoverflow that relates to this:
PHP & <noscript> combination to detect enabled JavaScript in browser
And with my very limited knowledge of jQuery have adapted it slightly to fit what i hope to achieve:
<script type="text/javascript">
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
})
// Put it in a var so you dont traverse the DOM unnecessarily.
var useJS = $("body").hasClass("js");
if(useJS){ // true or false if <body> has class JS.
// JS Enabled
$("#oldMenu").css("display", "none");
$("#newMenu").css("display", "inline");
} else {
// JS NOT enabled
$("#newMenu").css("display", "none");
$("#oldMenu").css("display", "inline");
}
</script>
Now the problem I am facing is that i cannot seem to get this script to register or make any visible difference. When i look at the body tag in the source there is no class on the body tag. The menu is not triggering as i thought it would and i am now after quite some time... Very confused.
If anyone could offer me some assistance, advice, information or indication that would help me to solve this current issue, i would really, REALLY appreciate that!
Thank you for taking the time to read through my line story! :)
EDIT:
#RomainPaulus suggested this and it works:
<script type="text/javascript">
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
// Put it in a var so you dont traverse the DOM unnecessarily.
var useJS = $("body").hasClass("js");
if(useJS){ // true or false if <body> has class JS.
// JS Enabled
$("#oldMenu").css("display", "none");
$("#newMenu").css("display", "inline");
} else {
// JS NOT enabled
$("#newMenu").css("display", "none");
$("#oldMenu").css("display", "inline");
}
})
</script>
Kenneth's response explains a lot, but I have noticed something else. Your code
var useJS = $("body").hasClass("js");
is executed before
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
})
You should put everything inside the $(document).ready(function(){ ... })
So I guess that explains why your code doesn't work.
The problem you face here is that, obviously when Javascript is not enabled, you're Javascript is not executing.
What you need to is hide the DIV by default with CSS. Then, when your page loads, show it through JS.
Javascript disabled => Div stays hidden, because no code is executed
Javascript enabled => div is hidden on load, but the script shows it
Also, if Javascript is disabled, Modernizr won't help, since it's a JavaScript library.

jquery ui.slider: add click event to display/hide handle

I am completely new to javascript and jquery. My programming knowledge is... nonexistent, I just started some days ago with some simple tasks like replacing a CSS class or toggling a div. So I want to apologize if I'm treading on someones toes by asking newbie-questions in here. But I hope that someone can help me and solve my problem.
I need to implement some sort of visual analog scale for a survey; ui.slider is perfect for that one. But I need the handle to be hidden by default. When the user clicks on the slider, the handle shall appear in the proper position. That should be fairly simple - at least I hope so - by just hiding the handle with CSS and changing it by a click event on the slider.
I use the following piece of code to wrap a normal div (a div is needed in my understanding to apply the jquery slider.js) to my input elements (they should be - at least visually - replaced by the slider) and pass the value of the slider to the input elements (needed for passing the values to a form). that works properly. (I do that instead of just putting a div in my DOM by default because I cannot influence some PHP scripts that will generate form elements of the survey and so on)
$(function () {
$.each($('.slider'),
function () {
obj = $(this);
obj.wrap('<div></div>');
obj.parent().slider({
change: function (event, ui) {
$('input', this).val(ui.value);
}
});
});
});
Hiding the slider-handle can be done by CSS as described above by changing style properties of a.ui-slider-handle. but when I add a normal click event to the slider (.ui-slider) that changes CSS properties of the handle, nothing happens. As far as my basic knowledge goes it should have something to do with the click event not working on generated DOM elements. Am I right with that one? And if yes: how can I solve this problem? Could someone provide me a piece of code for my function and explain it so I might comprehend what's exactly going on?
I read a tutorial about events on learningjquery.com but I have not made enough progresses the last few days since I started working with JS/jquery to comprehend the steps and translate it into my example/problem. And I am running out of time (I need this for a survey I have to make asap, that's why I hope someone could give me a hint so I can solve this little issue somehow).
Any reason you can't just include the show on the change event rather than a click? It's a bit cleaner code-wise rather than including a whole new event.
$(function() {
$('.slider').wrap('<div></div>').parent().slider({
change: function(event, ui) {
$('input', this).val(ui.value);
$('.ui-slider-handle').show();
}
});
});
Also, there was a bit of redundancy in the code - most jQuery functions return the object itself, so you can chain them. And you don't need that each function, since most jQuery functions also, when applied to a collection, run on all of them :)

Categories