directionally append an image tag - javascript

Hi I'm looking to move an image tag across divs based on mouse click, I have created a tile grid system with two different types of tile - "deathsquare" & "mapsquare". The player can only spawn inside the "mapsquare" tiles and I'm trying to use this for the moment too.
Grid -
<div id="28_25" class="deathsquare"></div>
<div id="29_25" class="deathsquare"></div>
<div id="30_25" class="deathsquare"></div>
<div id="1_20" class="mapsquare"></div>
<div id="2_20" class="mapsquare"></div>
<div id="3_20" class="mapsquare"></div>
<div id="4_20" class="mapsquare"></div>
This is the JSFiddle http://jsfiddle.net/zCZkA/16/
I can't seem to move the player up the "mapsquare" classes using the onclick arrow. Anyone have any suggestions?
Thanks!

You'll probably want to ensure that your rendered squares are systematically placed in order. Your squares currently are not. After you have sorted out that issue you can keep track of where your player is like so...
$('#up').click(function(){
var player = $('#player');
var currentDiv = player.parent().attr('id'); // gets you 3_5 or something like that
player.remove();
//do logic to move up
var placement = currentDiv.split('_');
var newSquare = [parseInt(placement[0])++,placement[1]].join('_');
$('#' + newSquare).append(player);
});

Related

Best ways to display width of multiple elements as text

Hi I'm looking at ways to specify the widths of a large number of objects on a page AND have each object's width displayed within it as text. The main aim is to avoid having a reference to the width anywhere (whether in the HTML, CSS or JS) more than once but I need potentially thousands of these objects on one page (currently I specify the width of the div and a text within it - too inefficient!).
So far I have this: https://jsfiddle.net/ghostfood/d6acdhq6/17/
<body onLoad="myFunction()">
<div id="object1" class="voteshare1" style="width:40.6%;">
This one is <span id="percentage1"></span></div>
<div id="object2" class="voteshare2" style="width:20.4%;">
This one is <span id="percentage2"></span></div>
<div id="object3" class="voteshare3" style="width:10.2%;">
This one is <span id="percentage3"></span></div>
<script>
function myFunction() {
var x1 = document.getElementById("object1").style.width;
var x2 = document.getElementById("object2").style.width;
var x3 = document.getElementById("object3").style.width;
document.getElementById("percentage1").innerHTML = x1;
document.getElementById("percentage2").innerHTML = x2;
document.getElementById("percentage3").innerHTML = x3;
}
</script>
</body>
The width must be a percentage but ideally would not include the percentage symbol in the displayed text (not sure how it's doing that as this is an example I found online then modified a bit - I do not know JS very well).
I've looked at D3 and amcharts for this briefly but I'm not sure they're best for handling hundreds of small stacked bar charts on one page and with lots of CSS control which is what I need. I may well be wrong!
Summary: Help me figure out a more efficient way of getting and displaying the (percentage) width (as set manually in HTML or JS and within a range of 10% to 100%) of an object within it as text (the caveat being that I need to do this for thousands of small objects on one page).
Set a common class to all divs that you want to get the width.
Select all of then with getElementsByClassName()
Loop through each one getting its width.
find the children span and add the string to it.
See below
function myFunction() {
var elements = document.getElementsByClassName("voteshare");
for (var i = 0; i < elements.length; i++){
var thisElement = elements[i];
var thisWidth = thisElement.style.width.toString();
thisElement.children[0].textContent += thisWidth;
}
}
<body onLoad="myFunction()">
<div id="object1" class="voteshare" style="width:40.6%;">
<span id="percentage1">This one is </span>
</div>
<div id="object2" class="voteshare" style="width:20.4%;">
<span id="percentage2">This one is </span>
</div>
<div id="object3" class="voteshare" style="width:10.2%;">
<span id="percentage3">This one is </span>
</div>
</body>
The problem with the JS is that you were referencing to object1 but the name of the <div> is object.
When a browser encounters an error, the execution of the script stops. That means that none of your code was running because the error was on the first line (of the function code).

Change background on hover of a draggable div

I have a small draggable division (black) and many nodes with different IDs beside it
I need a hovering effect when I drag the black element on the nodes. What I am doing in allowDrop function is:
var dragObj;
function drag(ev){
dragObj = ev;
}
function allowDrop(ev){
ev.preventDefault();
var Dragged = dragObj;
var Hovered = ev;
var leftIndent = Dragged.layerX;
var hoveredID = Hovered.target.id.toString().split('_');
var nodesOnLeft = Math.floor(leftIndent/12);
var startingNode = hoveredID[0]-nodesOnLeft;
for (i=1;i<=Math.floor(draggableElementLength/12);i++){
var toApplyCssID = startingNode.toString() + '_1';
var toApplyCss = document.getElementById(toApplyCssID);
$('#'+toApplyCssID).css('background-color','lightgreen');
}
}
basically I am using the layerX property to find out the distance between my mouse pointer and draggable division's border and adjusting that to calculate number of nodes where I have to apply new CSS and applying that by finding the ID of node.
This is working but its making the process very slow as it involves many calculations and its not the hover effect as its not going away when I am removing the draggable division.
Is there any other way to achieve this or do I need to make code changes in existing code.
thanks
Without the HTML and the rest of the script, I can only point you in the direction you should be taking in this kind of scenario:
Don't constantly repeat calculations (that do not change) in a loop, store them outside the function:
Use document.getElementById(toApplyCssID) for each node and store the
elements in an array
Get the distance from the mouse position to the required edge or
edges of the div (leftIndent) on initial drag/mousedown and store
that in a variable
Store Math.floor(draggableElementLength/12) in another variable (you
haven't shown where this originates, but it doesn't seem to change in
the function...)
Apply the CSS to the relavent elements (from the array of elements)
using the other stored values to select them
Remove the CSS on those that had it applied earlier
This may not be the ultimate solution, but these are some of the things you can look at to speed up what you (may) have currently.

What's the right way to run a javascript function without getting the object to "jump" right after the page loads

I have simple page with an object that gets a "top" property from the javascript.
How do I run the function without getting things on my page to "jump" ?
<script type="text/javascript">
function changeHeight () {
//Gets height
var h = window.innerHeight;
//alert(h);
console.log(h);
var categories = document.getElementById("cat").offsetHeight;
//alert(categories);
var x = 0.32 * categories;
var catTop = h - x;
//Gets cats
document.getElementById("cat").style.top = catTop+"px";
}
</script>
</head>
<body onload="changeHeight()" onresize="changeHeight()">
<div class="main">
<div class="cat" id="cat"></div>
</div>
</body>
</html>
I used "onload" on the tag to run the function. Which I know that's not so good.
The object jumps because you move it after the DOM has been rendered. That's what onload does: Make sure the DOM is complete and all loading/rendering has happened.
There are two solutions:
Put the script element after the node.
Use CSS to position the element
The first solution looks like this:
<div class="main">
<div class="cat" id="cat"></div>
<script>...</script>
</div>
At the time when the script is executed, the necessary DOM nodes are there. Unless your layout is complex, the offsets should be correct at this time. Note that many browsers start rendering while the page is loading. So there still might be a jump but less often, depending on the complexity of the page, browser optimizations, etc.
The second solution is to wrap your element in a container where you set the margin/padding until the cat element is naturally positioned correctly. The 0.32 would be translated to 32%. You need another element around it which has the correct height but which isn't visible.
To final solution should give body height: 100%, then add two containers inside. One for the content and the other to position the cat element. You will need to play with position style. Then
#cat { top: 32% }
should do the trick.

angularjs - mousedown & moving over elements while mouse down event?

To explain what I am trying to do I have created an example where you can play with:
http://plnkr.co/edit/usrmiNkj5YJY5SlV8ETw?p=preview
I want to draw multiple tiles green while my mouse is down.
This:
<div ng-mousedown="drawImage($parent.$index,$index)"></div>
works only when the mouse is going down on the element not outside.
Is there an way to check if the mouse is already down and draw the tiles green?
Please use the code I made to create an working example.
You'll have to include a few more event handlers, for mouseup and mousemove, like this
<div class="tile" ng-repeat="x in y track by $index" ng-class="x" ng-mouseup="removeFlag()" ng-mousedown="setFlag($parent.$index,$index)" ng-mousemove="drawImage($parent.$index,$index)"></div>
Then add the functions
$scope.drawImage = function(y,x){
if ($scope.mouseIsDown)
$scope.map[y][x] = "green";
}
$scope.setFlag = function(y,x){
$scope.mouseIsDown = true;
this.drawImage(y,x)
}
$scope.removeFlag = function(){
$scope.mouseIsDown = false;
}
This sets a flag when the mouse is down, and sets the color when the cursor moves over an element and the mouse is down.
PLNKR

javascript picture change not working correctly

Im in the middle of creating a site and have run into a bit of an issue. Basically what im working with is a collection of 3 pictures, two small, one large. What I'd like is that when you click one of the small pictures, it takes the spot of the larger picture. I have a javascript function that does this successfully but with one minor issue. Theres 3 of these collections of 3 pictures and thus when you click a small image to have it swap with the bigger one, the small image takes the spot of all of all 3 of the larger images instead of just the one for its section. Any suggestions? Thanks
the javascript function
$(document).ready(function(){
$('img').click(function(){
var url = $(this).attr('src');
var bigUrl = $(this).parents('.picture-container').find('.large-picture > img').attr('src');
$('.large-picture > img').attr('src', url);
$(this).attr('src', bigUrl);
});
});
what one of the sections looks like
<div class = 'main-content'>
<div class = 'picture-container'>
<div class = 'large-picture' style = 'width:50%;height:100%;float:left;'>
<img src = 'close_table_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'picture-content' style = 'float:right;width:45%;height:100%;'>
<div class='picture-title'>BOUTIQUE PRODUCTION STUDIO</div>
<div class='picture-text'>We built a boutique full service production studio that allows for one, two and three person filmed interviews and conversations. We have studio lights, a three camera set-up and remote monitoring. Additionally, our Infinity Wall creates a clean and professional look that allows the film to be about the message.</div>
<div class = 'small-picture-wrapper'>
<div class = 'small-picture' style = 'float:left;height:100%;'>
<img src = 'hair_and_makeup_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'small-picture' style = 'float:right;height:100%;'>
<img src = 'infinity_wall_dupontstudios.png' width = '100%' height = '100%'>
</div>
</div>
</div>
</div>
You're using a class selector for .large-picture when you're selecting it to apply the new image src. Presumably, all three sections have an element with this class, meaning all three are selected by your .large-picture selector. You need a more explicit selector to get ONLY the appropriate element.
You could use an id, or you could use parents() and find() in conjunction like you did previously:
$(this).parents('.picture-container').find('.large-picture > img').attr('src', url);

Categories