How do I assign draggable attribute to all instances - javascript

I am sure this is a simple question, but I am very new to using jquery, so please excuse me.
I am trying to write a function that will "deal" 5 randomly selected images and allow 3 of them (of the user's choice) to be dropped into a div.
I have set up an array to handle the randomization of images and have figured out how to make the div droppable. My first problem is that only the first image "dealt" is draggable. It seems to me that I have an logic error in the function dealCard()...
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var img = document.createElement("img");
img.src = "http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg";
img.id = "drag"
document.body.appendChild(img);
$('#drag').draggable();
removeCard(i);
}
function removeCard(c)
{
for (j=c; j <= numberOfCardsInDeck - 2; j++)
{
cardsInDeck[j] = cardsInDeck[j+1];
}
numberOfCardsInDeck--;
numberOfCardsInDeck--;
numberOfCardsInDeck--;
}
...For the life of me, I can't figure out why it doesn't reassign the draggable attribute to the rest of the images. Can anyone point me in the right direction?
My fiddle is: http://jsfiddle.net/LEHbc/22/

You are using an element id to make the elements draggable. After you add a second element, there is more than one element with id="drag", thus the draggable is applied only to the first one encountered in the DOM.
Using a class in this case would be preferable.

Use a little more of jquery's functionality to help you out and like #Kazimeiras said a class attribute and not an id.
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var $img = $("<img src='http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg' class='drag' />");
$("body").append($img);
$('.drag').draggable();
removeCard(i);
}
Updated fiddle: http://jsfiddle.net/LEHbc/23/

Related

Replacing an image with another in jquery using classes and IDs

I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!
I think there are at least four problems with your function:
To select by element id you need the # prefix, so $("#" + id) not $(id).
You don't want .find() because this is already the image in question.
Your image path in the html begins with "assets" but you don't include that in your Javascript.
If you only supply one funtion to .hover() that function will be called both when the mouse moves in and when it moves out. So you never change the image back.
The four lines of your function can be replaced with one line:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
});
This fixes problems 1-3 above. To fix problem 4 just supply a second function to change the src back when the mouse leaves:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
}, function(e) {
this.src = "assets/img/" + this.id + ".jpg";
});
You need to correct your selector.
JS:
$(".box-social").hover(function (e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg"; //make sure the path is correct
$('#' + id).attr("src", image); //Changed the selector.
});
Demo:http://jsfiddle.net/GCu2D/521/
try this
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg";
$("#"+id).attr("src", image);
});
you forgot "assets/" in your image link and your img selector is not corresct

Javascript onclick parameter

I have a question about "onclick" function in JavaScript. Here I have a div "InfoBar"
<div id="InfoBar"><br>
and two for loop
var src = new Array();
for(var i = 0; i < 2; i++){
src.push("el1","el2");
}
for(var j = 0; j < 2; j++){
doesFileExist(src[j]);
}
and a doesFileExist() and klick function
function klick(el){
alert(el)
}
function doesFileExist(urlToFile){
document.getElementById('InfoBar').innerHTML += '<br>' + '<a id="css" onclick="klick(urlToFile)" href="#" title="'+urlToFile+'">' + "link1 : " + urlToFile + '</a>';
}
now I've added a "onclick" function in "a href".
if I click on "link1:el1", I want to display as alert "urlToFile" string.
But I doesn't work.
In "a href" title="'+urlToFile+'" it works perfect, but in "onclick" doesn't work.
Can anyone help me?
Thanks in advance.
You are generating an attribute. That gets converted back into a function but the scope is broken.
Don't use intrinsic event attributes.
Minimise use of globals
Avoid generating HTML by mashing strings together (at best it is hard to read, at worst you get this sort of issue)
Use standard DOM:
var container = document.getElementById('InfoBar');
container.innerHTML = ""; // Delete any existing content
container.appendChild(document.createElement('br'));
var anchor = document.createElement('a');
anchor.setAttribute('id', 'css'); // You are running this function is a loop and creating duplicate ids. Use a class instead.
anchor.addEventListener('click', function (event) {
klick(urlToFile); // the local variable urlToFile is still in scope
});
anchor.setAttribute('href', '#'); // Why are you linking to the top of the page? Use a <button>
anchor.setAttribute('title', urlToFile);
anchor.appendChild(document.createTextNode("link1 : " + urToFile));
container.appendChild(anchor);
Event handles assigned this way won't work. You have to use JavaScript event handles. Means, you must create a new 'a' element, then bind a click event to it, and then append it as a child to the parent node. All this stuff is very good described on the web out there.

Create tag element dynamically and apply styles

I have created "myCanvas" div element dynamically and try to set styles to the div tag it throw the undefined exception. Please check my code and suggest me
// move the canvas, so it's contained by the same parent as the image
var imgParent = img.parentNode;
$('<div id="myCanvas">');
var can = $('myCanvas');
can.appendTo(imgParent);
// position it over the image
can.style.left = x + 'px'; //If set styles to can element, it's styles is undefined
What i did wrong here.. ? please anyone suggest me a right things..
Thanks,
Bharathi
Make is simple:
$('<div id="myCanvas">').appendTo(img.parentNode).css('left', x);
You don't need to select the myCanvas element because it hasn't been added to the DOM just yet (your selector wasn't right either). You can use this instead:
var imgParent = img.parentNode;
// By default when creating an element in jQuery, it returns an instance of the jQuery object created
var can = $('<div id="myCanvas">');
can.appendTo(imgParent);
can.style.left = x + 'px';
Replace
var can = $('myCanvas');
with
var can = $('#myCanvas');
[edit user="dholakiyaankit"]
QA asking for id not class
Antegias response should read
Replace ... with :
var can = $('#myCanvas');
as you have given it an id not a class, you cant select it in this way till its added to DOM, but you have a reference to it anyway in the variable can

make one element visible and 49 others invisible

I am absolutely new to javascript, so please bear with me.
I have 50 elements on my page with ids. All are set to visibility:hidden and position:fixed. I have a button that corresponds to each element. When a button is clicked, a javascript function is initiated which makes the corresponding element visibile and position:relative. Code looks something like this:
document.getElementById("id1").style.position='relative';
document.getElementById("id1").style.visibility='visible';
To ensure that only one element is ever visible and relative, I also need to make the other 49 elements hidden and fixed. How can I accomplish this without having to resort to the following sort of code:
function makeid1visibile()
{
document.getElementById("id1").style.position='relative';
document.getElementById("id1").style.visibility='visible';
document.getElementById("id2").style.position='fixed';
document.getElementById("id2").style.visibility='hidden';
document.getElementById("id3").style.position='fixed';
document.getElementById("id3").style.visibility='hidden';
document.getElementById("id4").style.position='fixed';
document.getElementById("id4").style.visibility='hidden';
// etc...
}
Any help would be appreciated, because with 50 elements, the number of lines of coding would be outrageous.
Should be able to handle it with a single loop, just pass in the number of the item you wish to show:
function makeIdVisible(id) {
document.getElementById("id" + id).style.position='relative';
document.getElementById("id" + id).style.visibility='visible';
for (var i = 1; i <= 50; i++) {
if (i !== id) {
document.getElementById("id" + i).style.position='fixed';
document.getElementById("id" + i).style.visibility='hidden';
}
}
}
give yours checkboxes classname "someclass" and select all elements by function documet.getElementsByClassName
You can write a function like this:
function makeVisible( id ){
var idList = ['id1','id2','id3','id4'];
for( var i = 0, l = idList.length; i<l ; i++ ){
document.getElementById(idList[i]).style.position='fixed';
document.getElementById(idList[i]).style.visibility='hidden';
}
document.getElementById(id).style.position='relative';
document.getElementById(id).style.visibility='visible';
}
Then you can use
makeVisible('#id1');
to make the id1 element visible

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?

Categories