Error in Javascript Code - javascript

if(e.target.id == "cited"){
alert(e.target.innerHTML);
if (document.getElementById(e.target.id).innerHTML == "[1]") {
display = "sometext1";
}
else if (document.getElementById(e.target.id).innerHTML == "[2]") {
display = "sometext2";
}
else if (document.getElementById(e.target.id).innerHTML == "[3]") {
display = "sometext3";
}
Alright, well when I hover over my [3] it displays "sometext2" when it should be displaying "sometext3". [2] and [3] is on the same page.
I did add a quick debug in to see if it picking up the wrong innerHTML by doing:
alert(e.target.innerHTML);
it displays the right one when I hover over in the alert message, but I don't know why it is displaying the wrong toolTip. Any help here?
document.onmousemove = function(e)
{
// e.target, e.srcElement and e.toElement contains the element clicked.
var x = e.pageX;
var y = e.pageY;
var display;
if(e.target.id == "cited"){
// alert(e.target.innerHTML);
if (document.getElementById(e.target.id).innerHTML == "[1]") {
display = "sometext1";
}
else if (document.getElementById(e.target.id).innerHTML == "[2]") {
display = "sometext2";
}
else if (document.getElementById(e.target.id).innerHTML == "[3]") {
display = "sometext3";
}
document.getElementById("toolTip").style.top = y-50+"px";
document.getElementById("toolTip").style.left = x+"px";
document.getElementById("toolTip").style.visibility = "visible";
document.getElementById("toolTip").innerHTML = "<p>"+display+"</p>";
}
else {
document.getElementById("toolTip").style.visibility = "hidden";
}

One problem seems to be that you have multiple elements on the same page with the same id. From your code, it seems that you have at least three elements with id cited.
If you want to refer to more than one element, you should use classes.

Bad way of fixing it:
document.onmousemove = function (e) {
var x = e.pageX;
var y = e.pageY;
var display;
if (e.target.id == "cited") {
if (e.target.innerHTML == "[1]") {
display = "sometext1";
} else if (e.target.innerHTML == "[2]") {
display = "sometext2";
} else if (e.target.innerHTML == "[3]") {
display = "sometext3";
}
document.getElementById("toolTip").style.top = y - 50 + "px";
document.getElementById("toolTip").style.left = x + "px";
document.getElementById("toolTip").style.visibility = "visible";
document.getElementById("toolTip").innerHTML = "<p>" + display + "</p>";
} else {
document.getElementById("toolTip").style.visibility = "hidden";
}
}
A better way would be to add event listeners to all of the elements and change their ids to classes, but that gets clumsy, so here's a jQuery solution:
$('.cited').mousemove(function(e) {
$('#tooltip').css({
top: e.pageY - 50 + 'px',
left: e.pageX + 'px',
text: $(this).data('tooltip')
});
}).mouseleave(function() {
$('#tooltip').hide();
}).mouseenter(function() {
$('#tooltip').show();
});
You'd change the HTML to this:
<span class="cited" data-tooltip="This is the tooltip text">Foo</span>
<span class="cited" data-tooltip="This is the tooltip text">Bar</span>

Related

Code that shows sticky button on scroll down & hide on scroll up

I want to repurpose this code from a video guide on website headers that hides when you scroll down and shows when you scroll up
<script>
"use strict";
OB_ready(OB_doWhenReady);
function OB_doWhenReady() {
// localize everything
var ooohBoi = window.ooohBoi || {};
// local scope variables
ooohBoi.prev_scroll_pos = window.scrollY || document.body.scrollTop;
ooohBoi.cur_scroll_pos;
ooohBoi.scroll_direction = 'init';
ooohBoi.prev_scroll_direction = 0;
ooohBoi.header = document.querySelector('#show-hide-header'); // header ID
ooohBoi.header_pos = {
top: ooohBoi.header.offsetTop,
left: ooohBoi.header.offsetLeft,
};
ooohBoi.header_height = OB_outerHeight(ooohBoi.header);
// show-hide header with ease/transition
ooohBoi.header.style.transition = 'all 0.3s ease';
// update header height on window resize
ooohBoi.updateHeaderHeight = function() {
ooohBoi.header_height = OB_outerHeight(ooohBoi.header);
}
// listen "scroll" event and decide what to do
ooohBoi.checkScroll = function() {
ooohBoi.cur_scroll_pos = window.scrollY || document.body.scrollTop;
if (ooohBoi.cur_scroll_pos > ooohBoi.prev_scroll_pos) ooohBoi.scroll_direction = 'down';
else if (ooohBoi.cur_scroll_pos < ooohBoi.prev_scroll_pos) ooohBoi.scroll_direction = 'up';
if (ooohBoi.scroll_direction !== ooohBoi.prev_scroll_direction) ooohBoi.toggleHeader(ooohBoi.scroll_direction, ooohBoi.cur_scroll_pos);
ooohBoi.prev_scroll_pos = ooohBoi.cur_scroll_pos;
}
// add or remove class based on the scrolling direction
ooohBoi.toggleHeader = function(scroll_direction, scroll_current) {
if (scroll_direction === 'down' && scroll_current > ooohBoi.header_height) {
OB_addClass(ooohBoi.header, 'im-hidden'); // for styling
ooohBoi.header.style.top = -1 * ooohBoi.header_height + "px";
ooohBoi.prev_scroll_direction = scroll_direction;
} else if (scroll_direction === 'up') {
OB_removeClass(ooohBoi.header, 'im-hidden');
ooohBoi.header.style.top = ooohBoi.header_pos.top + "px";
ooohBoi.prev_scroll_direction = scroll_direction;
}
}
// listen "scroll" and "resize" window events
window.addEventListener('scroll', ooohBoi.checkScroll);
window.addEventListener('resize', ooohBoi.updateHeaderHeight);
}
function OB_outerHeight(el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}
function OB_addClass(el, className) {
if (el.classList) el.classList.add(className);
else {
var current = el.className,
found = false;
var all = current.split(' ');
for (var i = 0; i < all.length, !found; i++) found = all[i] === className;
if (!found) {
if (current === '') el.className = className;
else el.className += ' ' + className;
}
}
}
function OB_removeClass(el, className) {
if (el.classList) el.classList.remove(className);
else el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
function OB_ready(fn) {
if (document.readyState != 'loading') fn();
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', fn);
else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') fn();
});
}
}
</script>
What I want to do is to repurpose this code for a sticky button at the bottom of screen (image)
How do I edit the code so that:
Instead of showing on scroll up and hiding on scroll down -> It shows on scroll down and hides on scroll up
Instead of sliding in and out from the top of the screen -> The button slides in and out from the bottom of the screen.
Thank you!

Javascript Function That Does Not Work if the Screen Width is More Than 516px?

I've been trying to create a mobile navigation menu with HTML and javascript.
So I created four links, a checkbox and a function that can hide the links when the checkbox is unchecked and unhide them when it is checked, it works fine, the only problem is I do not want the function to execute if the screen width is more than 516px.
Here's what I've got so far ("toggle" is the ID of the checkbox and "links" is the ID of the links):
function togglemenu() {
var toggle = document.getElementById("toggle");
var links = document.getElementById("links");
if (toggle.checked == true){
links.style.display = "block";
}
if (toggle.checked == false){
links.style.display = "none";
}
}
Here is my updated code:
function togglemenu() {
var toggle = document.getElementById("toggle");
var links = document.getElementById("links");
if (document.body.clientWidth <= 516) {
if (toggle.checked == true){
links.style.display = "block";
}
if (toggle.checked == false){
links.style.display = "none";
}
}
It still isn't working.
Here is the whole thing in jsfiddle...
You can use window.matchMedia(). See Receiving query notifications
if (window.matchMedia("(min-width: 516px)").matches) {
/* The viewport is at least 516 pixels wide */
} else {
/* The viewport is less than 516 pixels wide */
// do stuff
}
The if statement checks the document.body.clientWidth as recommended here: https://developer.mozilla.org/en-US/docs/Web/API/Document/width
document.querySelector('#test').addEventListener('click', test);
function test(event) {
let target = document.querySelector('#content');
target.innerHTML = `screen width ${document.body.clientWidth}px`;
if(document.body.clientWidth <= 516) {
target.innerHTML = Date.now().toString();
}
}
<button id="test">Test</button>
<div id="content"></div>
you can use below code to add a condition in your code.
if (window.screen.width > 516 ){
// do stuff
}
Here is link for more info.
use $(window).width() in if statement to get the width of the user window, then check if it is greater than 516px
JQUERY Code:
function togglemenu() {
var toggle = document.getElementById("toggle");
var links = document.getElementById("links");
if ($(window).width() > 516) {
//if width is greater than 516px
if (toggle.checked == true) {
links.style.display = "block";
}
if (toggle.checked == false) {
links.style.display = "none";
}
}
}
JS Code:
document.body.clientWidth use this instead for pure js, you're missing an end bracket } in function togglemenu()
function togglemenu() {
alert(document.body.clientWidth);//to check the current client width
if (document.body.clientWidth <= 516) {
alert("working");//just to check if it really works
var toggle = document.getElementById("toggle");
var links = document.getElementById("links");
if (toggle.checked == true) {
links.style.display = "block";
}
if (toggle.checked == false) {
links.style.display = "none";
}
}
}

How to display all child elements in JQuery/Javascript?

I am trying to display multiple child elements in jQuery but only the first child element gets displayed. I can force the browser to show all of them through Inspect and changing the css display from none to block. Can anyone help me find the problem in my code.I use Radio buttons, this is the code :
<script type="text/javascript">
$(document).ready(function () {
$('##radioButtonListSectionId input[type="radio"]
[checked="checked"]').each(function () {
ShowRadioButtonListDependentField(this, false);
});
});
$('##radioButtonListSectionId input[type="radio"]').change(function
() {
var result = $(this).val();
$('##uniqueID-hidden').val(result);
ShowRadioButtonListDependentField(this, false);
});
function ShowRadioButtonListDependentField(element, show) {
debugger;
var fieldKey = $(element).val(), children;
var currentId = element.attributes["currentid"].value;
if (currentId != 0) {
if ($('.main-dialogbox.modal.fade.in').length > 0)
children = $('.modal-body .control-group[parentid=' +
currentId + ']');
else if ($('.idea-task.open').length > 0)
children = $('.idea-task .control-group[parentid=' +
currentId + ']');
else
children = $('.control-group[parentid=' + currentId +
']');
if ($(element).is(":checked") && $(element).is(":visible"))
show = true;
else
show = false;
children.hide();
children.each(function () {
var keys =
this.attributes["parentOptionKey"].value.split("</br>");
var haschildren = this.attributes["haschildren"].value;
for (var i = 0; i < keys.length; i++) {
if (keys[i] == fieldKey) {
if (show) {
$(this).show();
show = false;
$(this.getElementsByClassName("ishidden")).val("False");
} else {
$(this).hide();
$(this.getElementsByClassName("ishidden")).val("True");
if (haschildren.toLowerCase() == "true") {
ShowCheckListDependentField(this,
false);
}
}
}
else {
$(this.getElementsByClassName("ishidden")).val("True");
}
}
});
}
}
</script>

Random "spawn" of divs

I'm trying to create a "spawn point" for a div. I have made it work and I have a working collision detector for it. There are two things I wanted to ask regarding my code.
How do I get my code to work with more than one player (window.i). - At the moment, after an hour of fiddling, I've only broken my code. This whole area screws up the collision detector, I have more than one player showing at times, but I'm unable to move.
How do I make it so that it detects the contact before it happens - I've tried working with the "tank's" margin and subtracting it's width, so that before it makes contact it calls an event, but it has been unsuccessful and completely stopped the collision function working.
I'm sorry that it's asking a lot, I really do understand that, but the issues come into eachother and rebound off so I thought it was best I put it all into one question rather than 2 separate ones an hour apart.
function animate() {
var tank = document.createElement("div");
tank.id= "tank";
tank.style.marginLeft="0px";
tank.style.marginTop="0px";
tank.style.height="10px";
tank.style.width="10px";
document.body.appendChild(tank);
x = parseInt(tank.style.marginLeft);
y = parseInt(tank.style.marginTop);
document.onkeydown = function () {
e = window.event;
if (e.keyCode == '37') {
if (x > 0) {
if (collisionDetector() == false) {
x = x - 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '39') {
if (x < 790) {
if (collisionDetector() == false) {
x = x + 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '38') {
if (y > 0) {
if (collisionDetector() == false) {
y = y - 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
} else if (e.keyCode == '40') {
if (y < 490) {
if (collisionDetector() == false) {
y = y + 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
}
}
}
window.lives = 3;
function playerSpawn() {
window.i = 1;
while (i > 0) {
var player = document.createElement("div");
randMarL = Math.ceil(Math.random()*80)*10;
randMarT = Math.ceil(Math.random()*50)*10;
player.id = "player";
player.style.marginLeft= randMarL + "px";
player.style.marginTop= randMarT + "px";
player.style.height="10px";
player.style.width="10px";
document.body.appendChild(player);
i--;
}
}
function collisionDetector() {
x1 = tank.style.marginLeft;
x2 = player.style.marginLeft;
y1 = tank.style.marginTop;
y2 = player.style.marginTop;
if ((x1 == x2 && y1 == y2)) {
return true;
} else {
return false;
}
}

hotspots not linking in product viewer

So using a script for 360 image rotation, i've set up a tags to act as hot spots and lead to different pages within a jquery mobile document. Everything works a desktop, but when i test the page on an ipad, none of the links do anywhere. Heres the script for the rotation.
<script>
jQuery(document).ready(function ($) {
var $product = $('#product'),
$imgs = $product.find(".child"),
imageTotal = $imgs.length - 1,
clicked = false,
widthStep = 4,
currPos,
currImg = 0,
lastImg = 0;
$imgs.bind('mousedown', function (e) {
e.preventDefault(); // prevent dragging images
})
.filter(':gt(0)').addClass('notseen');
$product.bind('mousedown touchstart', function (e) {
if (e.type == "touchstart") {
currPos = window.event.touches[0].pageX;
} else {
currPos = e.pageX;
}
clicked = true;
return false;
});
$(document)
.bind('mouseup touchend', function () {
clicked = false;
})
.bind('mousemove touchmove', function (e) {
if (clicked) {
var pageX;
if (e.type == "touchmove") {
pageX = window.event.targetTouches[0].pageX;
} else {
pageX = e.pageX;
}
widthStep = 4;
if (Math.abs(currPos - pageX) >= widthStep) {
if (currPos - pageX >= widthStep) {
currImg++;
if (currImg > imageTotal) {
currImg = 0;
}
} else {
currImg--;
if (currImg < 1) {
currImg = imageTotal;
}
}
currPos = pageX;
$imgs.eq(lastImg).addClass('notseen');
$imgs.eq(currImg).removeClass('notseen');
lastImg = currImg;
// $obj.html('<img src="' + aImages[options.currImg] + '" />');
}
}
});
});
</script>
I'm know its the script because when i remove it, the links work. Any ideas?
jQuery(document).ready() is not supported in jQM.
http://view.jquerymobile.com/1.3.0/docs/faq/dom-ready-not-working.php

Categories