Loop for in a .mousemove function - javascript

My problem is here :
$(document).mousemove(function(e){
for(i = 1; i < 7; i++){
var tt = document.getElementById("tooltip"+i);
document.getElementById("help"+i).onmousemove=function(event){
if(tooltip == 1){
$(tt).css({left:e.pageX+5, top:e.pageY+5});
tt.style.visibility= "visible";
}
}
document.getElementById("help"+i).onmouseout=function(event){
tt.style.visibility= "hidden";
}
}
});
With this code, the <div id="tooltip"+i> is showing right next to the mouse, but it's always the last "tooltip"+i, in this case tooltip6 which is showing.
I managed that to work by simply removing the loop for, and writing 6 times that next, each with a different i :
$(document).mousemove(function(e){
var i = 1;
var tt = document.getElementById("tooltip"+i);
document.getElementById(i).onmousemove=function(){
if(tooltip == 1){
$(tt).css({left:e.pageX+5, top:e.pageY+5});
tt.style.visibility= "visible";
}
}
document.getElementById(i).onmouseout=function(){
tt.style.visibility= "hidden";
}
});
In this case, it does what i want. It shows the tooltip1, when the mouse is over the <div id=help1>, and (e.g.) tooltip4 over the <div id=help4> if i use var i = 4.
I can obviously just write more and more like that as i add more tooltips, but i really don't understand why the adding of the loop is not working here.
My HTML code with the tooltips :
<span id=tooltip1>Health points of the rock. Each time it gets to 0, you get some stone</span>
<span id=tooltip2>Deeper you go, harder it is.</span>
<span id=tooltip3>Power of the Pickaxe.</span>
<span id=tooltip4>Go To the Village.</span>
<span id=tooltip5>Go To the Blacksmith.</span>
<span id=tooltip6>You can sell stone in the village.</span>
And HTML code with some of the help :
<div class=liststat id=help1>HP : <span id=hp>0</span></div>
<br>
<br>
<div class=liststat id=help2>Deep Level : <span id=lvlrock>0</span>m</div>
<br>
<br>
<div class=liststat id=help3>Pick Power : <span id=pickpower>0</span></div>
<br>
<br>
<div class=liststat id=help6>Stone : <span id=nstone>0</span></div>

Okay, so after reading the comment, i edited my code to make it simpler, and not adding any other listener, to not crash the script :
$(document).mousemove(function(e){
if(tooltip == 1){
var i = e.target.id;
var tt = document.getElementById("tooltip"+i);
tt.style.visibility = "visible";
$(tt).css({left:e.pageX+5, top:e.pageY+5});
document.getElementById(i).onmouseout=function(){
tt.style.visibility= "hidden";
}
}
});

Related

How to have a variable not reset when refreshing my website

<script>
var sum = 0;
var pressYet = false;
function changeIt() {
if(pressYet == false){
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
</script>
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id = "button" >Press If you are here</button>
SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.
I am very new to HTML so please be kind to me.
You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here
var sum = 0;
var pressYet = localStorage.getItem('pressYet');
function changeIt() {
if (pressYet == null) {
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
localStorage.setItem('pressYet', pressYet);
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
(function init() {
if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
})();
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id="button">Press If you are here</button>
You can check out the demo https://jsfiddle.net/5jyrk6s8/

Count divs that are hidden

I need a vanilla JS way to count the number of hidden divs on a page.
I have three divs with inline styles display: none. I thought this would work, but no luck:
var hiddenContainers = (document.getElementsByClassName(".emp-container").style.display == "none").length;
I have tried several solutions from SO and found a few JQuery ones that were successful, but what I'm writing needs to be done exclusively in regular old JavaScript.
EDIT: This works, but it seems like an unnecessarily roundabout way to get what I want:
var hiddenContainers = [];
var containers = document.querySelectorAll(".emp-container");
for (var i = 0; i < containers.length; i++) {
if (containers[i].style.display == "none") {
hiddenContainers.push(containers[i]);
}
}
function countclick(){
var m = document.querySelectorAll('.divs[style*="display:none;"]').length;
document.getElementById('count').innerHTML = "Hidden Divs: "+m;
}
<div class='divs' style="display:none;">a</div>
<div class='divs' style="">b</div>
<div class='divs' style="">c</div>
<div class='divs' style="display:none;">d</div>
<div class='divs' style="">e</div>
<div class='divs' style="display:none;">f</div>
<hr/>
<span id="count">Hidden Divs: 0</span><br/>
<button onclick='countclick();'>Count</button>

AngularJS - Textarea doesn't want clear after ng-click

I have problem with my textarea.
When I want clear her with ng-click, nothing happens ...
Can you help me ?
This is my code, you can test with Jsfiddle : My app
If you prefer see it here :
HTML :
<div ng-controller="Ctrl1">
<div><textarea id="yourid" ng-model="isWriting" ng-change="writeEvent(isWriting)"></textarea>
<span ng-if="displaySend == 1">Yann says :</span> {{isWriting}}
<p ng-click="sendYaah(isWriting); isWriting == ''">YAH!</p>
</div>
JS :
$scope.writeEvent = function(isWriting) {
$scope.imWriting = isWriting;
var empty = "";
if ($scope.imWriting != empty){
$scope.displaySend = 1;
// $scope.waitResponse = true;
} else {
$scope.displaySend = 0;
// $scope.waitResponse = false;
}
}
Thank for help !
Change ==(equality operator) to =(assignment operator) in ng-click
isWriting == ''
to
isWriting = ''
Forked Fiddle

using jquery next to find "nested" sibling

Perhaps there is a simple solution to this, but I am not able to figure it out.
I have a bunch of images sitting like this:
<div class='image-bar'>
<span>
<img class='my-image' src='blah1' id='1'>
</span>
<span>
<img class='my-image' src='blah2' id='2'>
</span>
<span>
<img class='my-image' src='blah3' id='3'>
</span>
</div>
Given the id of an image, I need to find the next and previous image to it, using jQuery.
Using 2 as example I tried following to get next image:
$('.image-bar').find('.my-image[id="2"]').next();
I think until my 'attribute equals' selector I am correct, but since the image with id 3 is not exactly a sibling, the next() is not working. How can I handle this? Any pointers are greatly appreciated!
This wont' work because the elements are wrapped in spans, you need to go relative to the parents of the images instead.
var next = $('.image-bar').find('.my-image[id=2]').parent().next().find('img');
var prev = $('.image-bar').find('.my-image[id=2]').parent().prev().find('img');
EDIT
Assuming you may have more images to deal with and are interested in the same functionality, you can do the following:
var elementId = "2";
var next = $('.image-bar').find('.my-image[id=' + elementId + ']').parent().next().find('img');
var prev = $('.image-bar').find('.my-image[id=' + elementId + ']').parent().prev().find('img');
If you have the id names in sequence I have another solution
var imgArray = $(".my-image"); // this will have an array with all images
Find image with id = 2
var id = 2;
imageArray[id-1]; // returns image with id 2
Find next image
imageArray[id];
Find previous image
imageArray[id-2];
NB: you need to check if the array index exists.
Fiddle here
var imgArray = $(".my-image"); // this will have an array with all images
console.log( getImage(2/* image id */, "next"));
function getImage(id, pos) {
var returnImage;
if(pos === "next") {
returnImage = imgArray[id] ? imgArray[id] : "";
}
else if(pos === "prev") {
returnImage = imgArray[id - 2 ] ? imgArray[id - 2] : "";
}
else {
returnImage = imgArray[id-1] ? imgArray[id-1] : "";
}
return returnImage;
}
Try using .filter() , .index() , .slice()
var imgs = $(".image-bar img");
var curr = imgs.filter("#2");
var i = curr.index(imgs.selector);
var prev = imgs.slice(i - 1, i);
var next = imgs.slice(i + 1, i + 2);
console.log("curr:"+curr[0].id
, "curr index:" + i
, "prev:" + prev[0].id
, "next:" + next[0].id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class='image-bar'>
<span>
<img class='my-image' src='blah1' id='1'>
</span>
<span>
<img class='my-image' src='blah2' id='2'>
</span>
<span>
<img class='my-image' src='blah3' id='3'>
</span>
</div>

Hiding text after clicking on something different

My goal here is to have the riddles in my page to be shown one at a time. My instructor has shown us a way using JavaScript variables. in my HTML I have two riddles shown as an example:
<h5>Question 1</h5>
<p onClick="revealAnswer('answer1','When it is turned into the teacher', 0)">When is homework not homework?</p><br/>
<span id="answer1" class="answers"></span><br/>
<hr>
<h5>Question 2</h5>
<p onClick="revealAnswer('answer2','An Umbrella', 1)">What goes up when rain comes down?</p><br/>
<span id="answer2" class="answers"></span><br/>
<hr>
in an external JavaScript, I have this code to expose the answers:
var isVisible = new Array();
isVisible[0] = false;
isVisible[1] = false;
function revealAnswer(answerId, answer, indexNum){
if(isVisible[indexNum]==false){
document.getElementById(answerId).innerHTML = answer;
isVisible[indexNum]=true;
console.log(answerId);
}
else{
document.getElementById(answerId).innerHTML = "";
isVisible[indexNum]=false;
}
My goal is when you click on "question 1", it shows you the answer, but when you click on "question 2" the answer to "question 1" goes away, and shows you the answer to "question 2". I am entirely new to JavaScript, but my best guess is to either add a new function, add an additional "if" or "else" to the existing "revealAnswer" function. What are your best recommendations?
var isVisible = new Array();
isVisible[0] = false;
isVisible[1] = false;
function revealAnswer(answerId, answer, indexNum){
if(isVisible[indexNum]==false){
var spanAnswer = document.querySelectorAll(".answers");
for(i=0;i < spanAnswer.length ; i++){
spanAnswer[i].innerHTML = '';
isVisible[i] = false;
}
document.getElementById(answerId).innerHTML = answer;
isVisible[indexNum]=true;
console.log(answerId);
}
else{
document.getElementById(answerId).innerHTML = "";
isVisible[indexNum]=false;
}
}
<h5>Question 1</h5>
<p onClick="revealAnswer('answer1','When it is turned into the teacher', 0)">When is homework not homework?</p><br/>
<span id="answer1" class="answers"></span><br/>
<hr>
<h5>Question 2</h5>
<p onClick="revealAnswer('answer2','An Umbrella', 1)">What goes up when rain comes down?</p><br/>
<span id="answer2" class="answers"></span><br/>
<hr>
Here you go
document.querySelectorAll will not work in IE
here is the traditional code which will work in IE as well
function revealAnswer(answerId, answer, indexNum){
if(isVisible[indexNum]==false){
var spanAnswer = document.getElementsByTagName("span");
for(i=0;i < spanAnswer.length ; i++){
if(spanAnswer[i].id == "answer"+(i+1)){
spanAnswer[i].innerHTML = '';
}
}
document.getElementById(answerId).innerHTML = answer;
isVisible[indexNum]=true;
console.log(answerId);
}
else{
document.getElementById(answerId).innerHTML = "";
isVisible[indexNum]=false;
}
}
Jquery would make your life much easier. Go take a look at this : http://www.w3schools.com/JQuery/jquery_hide_show.asp
To hide or show elements using Jquery you only have to do is give an id to your HTML elements as follows : <button id="hide">ButtonHide</button>
And then call an event on that button in JQuery :
$(document).ready(function(){
$("#hide").click(function(){
$("#hide").hide();
});
});
The #is a direct reference to the ID in your html making it easy to access it from your jquery.
If you wanted to hide the answer using jquery all you would have to do is :
Give and ID to it:
<p id="Question1Answer">blablabla</p>
<p id="Question2">blablabla</p>
Set an event on question 2
$(document).ready(function(){
$("#Question2").click(function(){
$("#Question1Answer").hide();
});
});
To make it clearer how to inlcude this into your code go check the link I posted at the top of the answer
Go check on the following link how to include Jquery : http://www.w3schools.com/jquery/jquery_get_started.asp
Here's a different approach. It toggles the visibility of the current answer, and then it hides all the other answers.
This simplifies the HTML, because you don't need any IDs. nextElementSibling grabs the answer that goes with the clicked question.
It also simplifies the JavaScript, because you don't need a global array to hold the visibility of each answer.
function revealAnswer(p) {
var ans= p.nextElementSibling,
all= document.querySelectorAll('.answers');
ans.classList.toggle('visible');
for(var i = 0 ; i < all.length ; i++) {
if(all[i] !== ans) all[i].classList.remove('visible');
}
}
.answers {
display: none;
}
.visible {
display: block;
}
<h5>Question 1</h5>
<p onClick="revealAnswer(this)">When is homework not homework?</p>
<p class="answers">When it is turned into the teacher</p>
<hr>
<h5>Question 2</h5>
<p onClick="revealAnswer(this)">What goes up when rain comes down?</p>
<p class="answers">An Umbrella</p>
<hr>
I know two ways to do this. One would be to put invisible radiobuttons on the page and to write the questions in their labels, but that's quite a peculiar hack. Let's do something simpler.
Instead of storing the state of all answers, you could just store which one is visible. Then, when you click on a question, the currently visible answer is hidden and the new answer is shown.
var visibleAnswer = null;
function revealAnswer(answerId, answer){
var answerElement = document.getElementById(answerId);
if(visibleAnswer) {
visibleAnswer.innerHTML = "";
}
if(!visibleAnswer || visibleAnswer.id !== answerElement.id) {
answerElement.innerHTML = answer;
visibleAnswer = answerElement;
} else {
answerElement.innerHTML = "";
visibleAnswer = null;
}
}
<h5>Question 1</h5>
<p onClick="revealAnswer('answer1','When it is turned into the teacher')">When is homework not homework?</p><br/>
<span id="answer1" class="answers"></span><br/>
<hr>
<h5>Question 2</h5>
<p onClick="revealAnswer('answer2','An Umbrella')">What goes up when rain comes down?</p><br/>
<span id="answer2" class="answers"></span><br/>
<hr>

Categories

Resources