Getting an images position within a ul javascript - javascript

I'm trying to get the position of an image with an a ul for example:
function myFunction(){
var img = document.getElementById("myID").querySelectorAll("img");
var x = x;
img[x].style.backgroundColor = "red";
}
The function will be ran when someone clicks the image.
I want a way to get var x = the number of the image that was clicked on.
I don't know jQuery So i'd appreciate if it was all in plane javascript thanks.

Thats an x y problem. Probably:
//wait for all clicks
window.addEventListener("click",function(event){
//check if it has a parent with id myID
var e=event.target;
while(e!==document.body && e.id!="myID"){
e=e.parent;
}
if(e.id=="myID"){
//set a backgroundcolor to the clicked element. May also check if Node is IMG
event.target.style.backgroundColor="red";
}
});

Related

Trying to Set the Index of a td in jQuery

In the process of creating a tile-swap puzzle game for my jQuery class. Right now I'm working on trying to make the clicked tile switch with the blank tile (I'll figure out how to limit it to adjacent tiles afterwards). I've stored indexes of both indexes in new variables, but I can't figure out how to assign a variable as the td elements index.
$(document).ready(function(){
$('img').click(function(){
var tileSelected = $(this); //grab the clicked tiles index
var tileIndexOld = $("img").index(tileSelected);
var blankTile = $("#blank"); //grab the blank tiles index
var blankIndexOld = $("img").index(blankTile);
var tileIndexNew = blankIndexOld; //swap tile and blank indexes
var blankIndexNew = tileIndexOld;
$(this).attr("index", tileIndexNew);
$("#blank").attr("index", blankIndexNew);
});
});
I've also tried doing things like $(tileSelected).index(tileIndexNew); and $(this).index() = tileIndexNew; etc. I just can't seem to figure out how to overwrite with the new index.
Edit:
Okay, I've been shown the wickedness of my (attempted) index swapping ways! Still working on the solution, but I'm changing tracks and focusing on altering the src's as suggested by Starscream1984. I'll update again once I've got it figured out, many thanks to all!
Solution:
After trying it three different ways (with multiple sub-variations) this is what I ended up with:
$(document).ready(function(){
$("td").click( function(){
var tileVertical = $(this).index(); //get clicked tiles vertical position via its td
var tileHorizontal = $(this).parent().index(); //get clicked tiles horizontal position via its tr
var blankTile = $("#blank").parent(); //getting the td that contains the blank tile
var blankVertical = blankTile.index(); //get blank tiles vertical position (via its td)
var blankHorizontal = blankTile.parent().index(); //get blank tiles horizontal position via its tr
if( Math.abs(blankVertical - tileVertical) + Math.abs(blankHorizontal - tileHorizontal) == 1) //check if clicked tile is adjacent to the blank tile
{
blankTile.empty().html( $(this).html() ); //put the tile html into the blank slot
$(this).html("<img id='blank' src='blank.jpeg' width='200px' />"); //fill the tile slot with the blank, ID IS CRITICAL!!!!
} //function will only run once if id is omitted from this tag!!!
return 1;
});
});
My original approach tried to use the index as a quick and dirty variable to swap out. What I discovered was that the index in this case is simply more like a map with x and y coordinates. It was the inner html of the table cell that needed to be swapped, not the index itself.
You need to move the elements around using jQuery DOM modification methods. This solution assumes that each tile is contained in a DIV in the grid.
$('img').click(function(){
var tileSelected = $(this);
var parentSelected = tileSelected.parent();
var blankTile = $("#blank");
var blankParent = blankTile.parent();
parentSelected.append(blankTile);
blankParent.append(tileSelected);
});
A)
$('img').each(function(index, elem){
console.log(index);
});
B)
$('img').click(function(){
var index = $(this).index();
//or
//var index = $('img').index($(this));
console.log(index);
});
Are the right ways. So your code seems to be correct. Are you sure that all imgages exists at the moment you run the function? Do you noticed that your selector find all img in DOM?
If you want to assign an index variable for the td, one approach to do it dinamically is the following:
$(document).ready(function(){
var tdArray = $("td");//grabs all td elements
for(i = 0; i < tdArray.length; i++){
$(tdArray[i]).attr('data-index',i);//adds a data-index attribute on each one
}
});
You could then handle a click event like this:
$("td").click(function(){
alert($(this).attr('data-index'));
});
To keep track of your blank tile, you could simple assign its data-index to a global variable.

click based on position rather than element

can I create a function that takes x and y coordinates, and will click the document at those coordinates?
by looking at this question I set up some sample code in a jsfiddle, here is that code (it does not work)
var e = new jQuery.Event("click");
e.pageX = 10;
e.pageY = 10;
$("button").click(function(){
$(document).trigger(e);
});
what I thought the above code would do is click in the document at position (10,10), and because that section of the document is where the item that needs to be clicked is, it should do the same as would clicking the item. But it does not...what am I doing wrong?
why
why would I do this when I could just simply do something like:
$("button").click(function(){
$('.box').click();
});
well in certain circumstances, that is not possible. for example, clicking a specific div inside an iframe outside of the domain. I cannot click what is inside it through code because I don't have access to it's body. But if I know the position of that div in my own document and force the viewer to click over it, then that would work!
Well, you used
$('button').click(function(){...});
Maybe, you meant,
var e = new jQuery.Event("click");
e.pageX = 10;
e.pageY = 10;
$(document).trigger(e);
var x=e.pageX;//get the current mouse coordinates
var y=e.pageY;
function between(val, min, max)//this fun specifies the range!!!
{
return val >= min && val <= max;
}
Just a sample code.
$('body').click(function(){
if(between(x,your_conditional_min_x,your_conditional_max_x) && between(y,your_conditional_min_y,your_conditional_max_y))
//execute some code if its in my region!!!
});
In the above code--
your_conditional_min_x and y & your_conditional_max_x and y are the custom x and y positions that you want enclose your click in.
let me know if you are not clear with the code!!!

JavaScript, using a function to change the text displayed in a HTML <p> tag

I have a HTML5 canvas, which is displaying a number of images and a paragraph of text on the page underneath the canvas. I want the text in the paragraph to be updated to display a different element from a JS array depending on which image the user clicks on.
Currently, I have a 'mousedown' function that looks like this:
_mousedown: function(evt) {
this._setUserPosition(evt);
var obj = this.getIntersection(this.getUserPosition());
if(obj && obj.shape) {
var shape = obj.shape;
this.clickStart = true;
shape._handleEvent('mousedown', evt);
isClickOnImage(evt);
var id = shape.id;
selectTip(id);
}
//init stage drag and drop
if(Kinetic.DD && this.attrs.draggable) {
this._initDrag();
}
}
I tried using the line var id = shape.id to update the ID that's being passed to the function, so that it will get the correct element from my 'tips' array, but for some reason, when I view the page in the browser, and click on an image, the text beneath the canvas is not updated. It seems that this function is not updating the 'id' variable to the ID of whichever image has been clicked.
After looking into this, it seems to me that I will want to use a loop inside the 'mousedown' function, that will take the 'id' of the image on which the click has been detected, and loop through my 'sources' array (which is where all of the images have been loaded from the HTML into the JS), checking at each position whether the image stored at that location has the same ID as that of the image that has been clicked on. If it does, the loop should set the text to the text stored at that position of the array, and if not, it should continue looking through the array until it find it. Would this make sense? I tried adding the following code to the 'mousedown' function, but it doesn't change the text as I expected:
var imageCheckArray = 0;
while(imageCheckArray < sources.length){
if(shape.id == sources[imageCheckArray]){
selectTip(imageCheckArray);
} else {
imageCheckArray++;
}
}
Is there something I'm missing from the loop?
The code for the whole function currently looks like this:
_mousedown: function(evt) {
this._setUserPosition(evt);
var obj = this.getIntersection(this.getUserPosition());
if(obj && obj.shape) {
var shape = obj.shape;
this.clickStart = true;
shape._handleEvent('mousedown', evt);
isClickOnImage(evt);
/*This line needs to get the element of the sources array that has been selected,
and then select the element at the same position from the tips array.*/
//var id = null;
var imageCheckArray = 0;
while(imageCheckArray < sources.length){
if(shape.id == sources[imageCheckArray]){
selectTip(imageCheckArray);
} else {
imageCheckArray++;
}
}
//var id =
//selectTip(id);
}
//init stage drag and drop
if(Kinetic.DD && this.attrs.draggable) {
this._initDrag();
}
}
Edit 11/01/2013 # 16:10
The code for selectTip is:
function selectTip(id){
$("#tipsParagraph").text(tips[id]);
}
and I've put a jsFiddle up here: http://jsfiddle.net/cd8G7/ although the 'result' panel is not showing what I actually see when I view the page in my browser- I get the canvas with all of the images displayed, and the paragraph underneath the canvas shows the text from the first element of my 'tips' array.
Edit 23/01/2013 # 13:50
Here's my isClickOnImage function:
function isClickOnImage(event){
var clickX = event.clientX;
var clickY = event.clientY;
//var imageCheckIteration = 0;
while(imageCheckIteration < sources.length){
if((clickX > sources[imageCheckIteration].x && clickX < sources[imageCheckIteration].x + imageWidth) &&
(clickY > sources[imageCheckIteration].y && clickY < sources[imageCheckIteration].y + imageHeight)){
/*This is where I need to print the variable that holds the text I want to display, but I need to display its contents
outside the canvas, in the <p></p> tags below. */
console.log("Click on image detected");
document.getElementById("tipsParagraph").innerHTML = sources[imageCheckIteration].data-tip /*tips[imageCheckIteration]*/;
} else {
document.getElementById("tipsParagraph").innerHTML = "";
}
}
}
What I intended that this function do is, capture the X & Y coordinates of any click on the canvas, and store them in the variables "clickX" and "clickY". Then, I have a variable called "imageCheckIteration" that has been initialised to 0, and while this variable is less than the length of my "sources" array (which is the array where all of the images have been stored), the function should check whether the click was on an area of the canvas that is covered by one of the images in the array.
If it was, then a console log should display the message "click on image detected", and the line
document.getElementById("tipsParagraph").innerHTML = sources[imageCheckIteration].data-tip;
should set the value of the "tipsParagraph" to be the value of the 'data-tip' attribute of whichever image is at the 'imageCheckIteration' position of the 'sources' array. If the click was detected on an area of the canvas that does not have an image displayed, then the value of the "tipsParagraph" should be set to hold nothing.
However, for some reason, when I view the page in the browser, the 'tipsParagraph' displays the text "This is where the text will be displayed", which is its default value, so that's fine. But, when I click on an image, or click anywhere else on the canvas, the text displayed in the 'tipsParagraph' is not updated.
I can't figure out why this is- can someone point me in the right direction? Does it mean that my isClickOnImage(event) function is never being called?
I simplified the way you are getting a reference to an image through the canvas. The trick here is to swap the z-index of the canvas and the image container and grab the reference to the image on the mouse up event. I don't know of a clean way to get elements behind a canvas, hence the workaround.
$('canvas').bind('mousedown', function(e) {
$('section').css('z-index', 4);
});
$('img').bind('mouseup', function(e) {
$('#tipsParagraph').text($(this).attr('id') + ":" + $(this).attr('alt'));
$('section').css('z-index', 2);
});
The second portion here is grabbing some attributes from the image itself and updating the text inside your div.
You can see more of the solution here.

Variables within function is null

I have the following function:
function slideDown() {
//get the element to slide
sliding = document.getElementById('slideDiv1');
//add 1px to the height each time
sliding.style.height = parseInt(sliding.style.height)+1+'px';
t = setTimeout(slideDown,30);
if (sliding.style.height == "401px") {
clearTimeout(t);
}
}
which is called within this function:
function addDiv(nextImageSlide) {
//finds the src attribute of the image nested in the Li
elemChild = nextImageSlide.firstChild;
imageSrc = elemChild.getAttribute('src');
//loops and creates six divs which will be the slices. adds background property etc
for (i = 0, j = 0, k = 1; i< = 19; i++, j++, k++) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'new-div');
newDiv.id='slideDiv' + k;
newDiv.style.height = '1px';
newDiv.style.background = 'url(' + imageSrc +') scroll no-repeat - '+39.5 * j + 'px 0';
var a = document.getElementById('content');
a.appendChild(newDiv);
}
slideDown();
}
Which is called within another function that defines nextImageSlide. It later removes all the divs that it just made.
The idea is for an image gallery. When the user hits the next button, I want slices of the next image to slide down to show the next image. Those slices are then taken away and the new image revealed.
I would like something like this: http://workshop.rs/projects/jqfancytransitions/.
It's for an assignment so we have to write all the code ourself and this is the best way I can think to replicate it. The only problem is that I keep getting an error:
'sliding is null. sliding.style.height = parseInt(sliding.style.height)+1+'px';'
No matter what I do I can't get rid of it. The thing is if I define sliding as a totally different id, (for example I made a random little div outside of everything), it working.
This error shows when I try to access the divs, it just made that it throws a hissy fit.
Anyone see any errors in my code?
Hopefully this is just a typo while pasting into the site here, but:
car a = document.getElementById('content');
^---syntax error, which'll kill your entire script - var?

javascript get text at mose postion

How can I get text at mouse position?
I have now some like this
document.body.onmousemove = function(){
//todo:Get text at mouse position
}
One way of doing so is using [PrototypeJs][1]
Try this one let me know if there is any problem
$(document.body).observe('click', respondToClick);
function respondToClick(event) {
var element = event.element();
var source = element.innerHTML;
}

Categories