Target class name but call function on unique ID - javascript

Ok I'm going to run this on the slowest ASP box I've ever seen before, so I'm not looking to use jQuery, I know it would make everything a lot easier but I need to keep my code as small as humanly possible. I'm targeting users with the slowest internet I've ever seen and loading the entire jQuery file will be to much for their internet to take. So I'm not looking to use jQuery for this script.
I'm trying to make a script that when the user hovers over the thumbnail the larger image pops up. I'm using the following javascript to achieve this:
var hoverImage = document.getElementById("largeImage");
function hoverZoom(selector) {
this.node = document.querySelector(selector);
if(this.node === null) {
console.log("Node not found");
}
return this.node.id;
}
hoverZoom.prototype.show = function(x, y) {
var largeImageSrc = this.node.name;
hoverImage.style.display = "block";
var largeWidth = hoverImage.offsetWidth;
var largeHeight = hoverImage.offsetHeight;
hoverImage.style.top = y - (largeHeight / 2) + "px";
hoverImage.style.left = x - (largeWidth / 2) + "px";
hoverImage.style.position = "absolute";
hoverImage.style.background = "url(" + largeImageSrc + ")";
}
hoverZoom.prototype.hide = function() {
hoverImage.style.display = "none";
}
hoverZoom.prototype.checkCoords = function(x, y) {
var id = document.getElementById(this.node.id);
var elemTop = id.offsetTop;
var elemLeft = id.offsetLeft;
var elemHeight = id.offsetHeight;
var elemWidth = id.offsetWidth;
console.log(x + " " + y + " " + this.node.id + " " + id + " " + elemHeight + " " + elemWidth + " " + elemTop + " " + elemLeft);
if(x >= elemLeft && x <= elemLeft + elemWidth && y >= elemTop && y <= elemTop + elemHeight) {
return true;
}
}
document.body.onmousemove = function(e) {
e = e || window.event;
while(hoverZoomPI.checkCoords(e.clientX, e.clientY) === true) {
var target = e.target || e.srcElement,
offsetX = e.clientX,
offsetY = e.clientY;
return hoverZoomPI.show(offsetX, offsetY);
}
hoverZoomPI.hide();
}
var hoverZoomPI = new hoverZoom(".test");
My problem is that when I hover over another image with the same class name nothing happens. But when I hover over the first image with the class name it works.
I've set up a jsFiddle with all my code and an example: http://jsfiddle.net/f7xqF/
Thanks everybody for their help. I can't say enough about how much you guys have helped me over the last few years.

You should use document.querySelectorAll instead document.querySelector to get an LIST of all nodes, not just first one. After that u should of course attach callbacks to all of collected elements.

Related

How to change image height with one provided by the user (prompt)

Second part of the code (starting with var newHeight) does not work - what is wrong?
/* var getDim = document.getElementsByTagName("img");
var a = getDim[0].height;
var target = document.getElementById("target");
target.innerHTML = "<p>This image has" + " " + a + " " + "pixels.</p>"; */
var newHeight = prompt("Provide new height"); // 2nd part
var image = document.getElementsByTagName("img");
var theOne = image[0];
if (isNaN(newHeight) === false) {
theOne.style.height === newHeight;
}
else {
alert("Provide a proper value!")
}
You have to change this line:
theOne.style.height = newHeight;
instead
theOne.style.height === newHeight;
The second one is an expression, not an assignment.

How to make element disappear once its created with event listener (pure Javascript)

I've been googling for hours and trying out different methods and can't get this to work.
I'm trying to do is: if there is no box, then add a box. If there is a box where you're clicking, then remove the box.
So far, it removes a box but automatically adds a new one, leaving a box on the screen when there should be none.
How do I get the box removed when someone clicks on it -- in pure Javascript.
Here is my jsfiddle so you can see what's happening. https://jsfiddle.net/on6z83ko/10/
Code:
addEventListener('click', createBox);
function createBox(event){
var box = document.createElement('div');
document.body.appendChild(box);
box.className = "box";
box.style.visibility="visible";
box.style.left = event.pageX + 'px';
box.style.top = event.pageY + 'px';
var mouse = event.currentTarget;
mouse.click = (mouse.click || 0) +1;
console.log(mouse.click);
box.addEventListener("click", function(){
var deleteBox = document.getElementsByClassName('box');
if(deleteBox){
box.remove();
}
});
}
document.addEventListener('click', createBox);
function createBox(event){
var target = event.target;
if(target.className === 'box'){
target.parentNode.removeChild(target);
} else {
var box = document.createElement('div');
box.className = "box";
box.style.visibility="visible";
box.style.left = event.pageX + 'px';
box.style.top = event.pageY + 'px';
document.body.appendChild(box);
}
}
From how I read the question, this will not add a box when there is one on the screen, and remove it when it
is clicked, then add another on the next click.
https://jsfiddle.net/on6z83ko/40/
addEventListener('click', createBox);
var box;
var boxBounds = {
Left: 0,
Right: 0,
Top: 0,
Bottom: 0
};
function createBox(event) {
if (box == null) {
box = document.createElement('div');
var target = event.target;
document.body.appendChild(box);
box.className = "box";
box.style.visibility = "visible";
box.style.left = event.pageX + 'px';
box.style.top = event.pageY + 'px';
return;
}
//alert(event.pageX + "," + event.pageY);
boxBounds.Left = parseInt(box.style.left, 10);
boxBounds.Right = boxBounds.Left + 100;
boxBounds.Top = parseInt(box.style.top, 10);
boxBounds.Bottom = boxBounds.Top + 100;
//alert("");
//alert("L" + boxBounds.Left + " R" + boxBounds.Right + " T" + boxBounds.Top + " B" + boxBounds.Bottom);
//remove if in bounds of box
if ((event.pageX >= boxBounds.Left) && (event.pageX <= boxBounds.Right) &&
(event.pageY >= boxBounds.Top) && (event.pageY <= boxBounds.Bottom)) {
//alert("InBOX");
document.body.removeChild(box);
box = null;
return;
}
}
Is this what you're looking for?
JSFiddle Example
This was the key-point:
if(target.classList.contains('box')){
target.remove();
}
You can create an even handler on your box and stop propagation to prevent main click event, and remove the box in that event handler. I cant edit your code from my phone :(

How can I make a div from elsewhere on the page float next to a checkbox when the checkbox is clicked?

I have a checkbox. I want a div which is on the bottom of my page to float next to the checkbox when the checkbox has been clicked.
How can I do this?
Here is some code that is working for my mouseovers. Its pretty far beyond my level. Is there an easier way, or way I can use this code for checkboxes as well?
function addreflinkpreview(e) {
var c;
var d = "srcElement";
var f = "href";
this[f] ? c = this : c = e[d];
ainfo = c.className.split('|');
var g = document.createElement('div');
g.setAttribute("id", "preview" + c.className);
g.setAttribute('class', 'reflinkpreview');
g.setAttribute('className', 'reflinkpreview');
if (e.pageX) {
g.style.left = '' + (e.pageX + 50) + 'px'
} else {
g.style.left = (e.clientX + 50)
}
var h = document.createTextNode('');
g.appendChild(h);
var i = c.parentNode;
var j = i.insertBefore(g, c);
new Ajax.Request(ku_boardspath + '/read.php?b=' + ainfo[1] + '&t=' + ainfo[2] + '&p=' + ainfo[3] + '&single',{
method: 'get',
onSuccess: function(a) {
var b = a.responseText || _("something went wrong (blank response)");
j.innerHTML = b
},
onFailure: function() {
alert('wut')
}
})
}
One way you may be able to achieve this is with positioning and transitions. Take the screen coordinates of the click event and then absolute position the div next to the coordinate by adding or subtracting from the x-coordinate.

function doesn't execute on jquery document ready

I have a javascript function that resize and centers images based on the surrounding container size (that in turn depend on the window size). I use jquery as js framework. The function need to be executed after document load (on document ready) but also when and if the user changes size of the browser, ie I have the following running in the html-document:
$(document).ready(function(){
fixImageSizes();
});
$(window).resize(function() {
fixImageSizes();
});
But for some unknown reason the function is only executed when a user resizes the browser and not after loading. Can anyone please help with this?
(my function is below for knowledge...)
function fixImageSizes()
{
var cw = $('#imagecontainer').width();
var ch = $('#imagecontainer').height();
$('#imagecontainer img').each(function()
{
var iw = $(this).css('width');
var ih = $(this).css('height');
if (parseInt(iw) < parseInt(cw)) // image width < viewport
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) < parseInt(ch)) // image height < viewport
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) > parseInt(ch) && parseInt(iw) > parseInt(cw)) // viewport smaller than image, shrink image
{
if (parseInt(ch) - parseInt(ih) > parseInt(cw) - parseInt(iw)) // difference is less on height
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
else // difference less on width
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
}
});
You should use the load event instead of the ready event.
The ready event runs after the document has loaded, but before the images has loaded, so you won't have the correct size of all elements.
The function is probably executing (you can double-check with a simple alert), but the images you are "fixing" is probably not loaded yet. You can use the window.onload event or listen to the image load event like this:
var scale = function() {
// rescale
};
$('#imagecontainer img').each(function() {
this.complete ? scale.call(this) : $(this).load(scale);
});
Try this:
$(window).load(function (){
fixImageSizes();
});

FInd out position of html element in iframe

I want to find out the position of an element which is in iframe. I am trying ot use:-
//Function to find the position of element on page
function getElementPosition(elem){
var posX = 0;
var posY = 0;
while(elem!= null){
posX += elem.offsetLeft;
posY += elem.offsetTop;
elem = elem.offsetParent;
console.log("In function:" + elem.tagName + " " + posX + " " + posY);
}
return { x : posX, y : posY };
}
To get the list of all elements of iframe,
var doc1 = $('#page1').get(0).contentDocument; // page1 is id of iframe element
var list1 = doc1.getElementsByTagName('*');
console.log(list1.length); // Printing correctly
var index = prompt("Enter element index");
var elem1 = list1[index];
var pos1 = getElementPosition(elem1);
console.log("Positions:" + pos1.x + " " + pos1.y);
But this is not working. Initially elem is not null but elem.offsetParent is null in every case. Am i doing some wrong ?
For some elements, it is working fine. But for some elements, offsetParent is coming null and so their offsetLeft is 0 and offetTop is 0.
Is there any other way to find out position of each element.
Thanks in advance..
You already appear to be using jQuery. Why not let jQuery do the heavy lifting for you?
http://api.jquery.com/position/
http://api.jquery.com/offset/

Categories

Resources