I'm trying to figure out what the best way would be to set up a website interface that has a large centre 'tile' (basically a div with rounded corners, a variable background image, and text on it) that acts as the hub of the interface, around which I have smaller tiles which are clickable as link, e.g. one tile will lead to a photo gallery etc... However I need these smaller tiles to be moveable i.e. I would like them to visibly whisk away off the screen (in a specific direction) before the next set of tiles enters the screen.
(Ideally they would be the same set of tiles, they would simply go off screen to 'change' as it were and come back as the new set of tiles - An ideal example would be of clicking on the photo gallery tile, all the main tiles whisk away off screen, to be replaced by more tiles representing individual photos in the gallery)
I have no issues with the CSS of round corners and positioning my tiles etc... but I'm currently trying to get the tiles to actually move using the code referenced here: Alter CSS class attributes with javascript?
I can't get it to work. I've set up one of my test tiles to make just one change to the width of another test tile using the above-referenced code when it detects a mouseover event on the div, but it appears not to work.
Here's my code, if you can spot any errors, but primarily I'd also like to hear if you have any better suggestions of reaching the design state I'm looking for:
var style;
function changeFoo() {
if(typeof style == 'undefined') {
var append = true;
style = document.createElement('style');
}
else {
while (style.hasChildNodes()) {
style.removeChild(style.firstChild);
}
}
var head = document.getElementsByTagName('head')[0];
var rules = document.createTextNode(
'.tiletest2 { border:4px solid #999; background-color:#999; width: 50px; border-radius:32px; }'
);
style.type = 'text/css';
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
if(append === true) head.appendChild(style);
}
The onmouseover event looks like this:
<div class="tiletest1" onmouseover="changeFoo()">
<br/><br/>
SAMPLE left
<br/><br/>
Try using a JavaScript library like http://jquery.com/. You can also get plugins like http://jqueryui.com/ for the kinds of effects you're describing.
I agree with TimS to go with jquery, specifically you will want to use the .animate()function.
This will make it much easier on yourself since you can easily control the speed and time the animation plays and you may be able to easily remove div(s) with the .hide() function, which gives you many options of what kind of animation you could use to close it.
Related
When you scroll on a page, the page shows an element, I want to be able to specify this element and
do code with it using JS, is this possible? I tried something but it had another problem..
What I tried was,
let section = document.getElementById('out');
window.onscroll = function() {
if (window.scrollY >= 678) {
document.getElementById('out').style.color = "red";
} else {
document.getElementById('out').style.color = "black"
}
}
I didn't use animate here, I just made sure it works, and it did, well almost, because if you zoom in/out it ruins it, I think that's because I got the 678 by going to the button and printing scrollY manually, is there anyway to make that automatic, so it works on any element I need?
I searched a lot and can't seem to find what I need, the solutions need jQuery, I need a solution only with html, css, and javascript.
In the future the solution will be css scroll timelines, but as that feature is at the time of writing experimental and is not supported by major browsers you can use intersection observers.
Quoted from MDN:
The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount.
To animate a component when it is in or out of view, you can give animated elements a .hidden class in your html markup and create an intersection observer which appends the .shown class to .hidden elements when they are in view.
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => entry.target.classList.toggle(“shown”, entry.isIntersecting))
})
const hiddenElements = document.querySelectorAll(“.hidden”)
hiddenElements.forEach((el) => observer.observe(el))
Then you can just apply transitions under a <selector>.shown css rule.
I am calling the following function and passing it the location of an image:
function show_image(source) {
var img = d3.select("#right-section").append("img").attr("src",source)
img.transition().duration(5000).easeLinear;
}
Here is the function that uses some JQuery to empty the relevant HTML div object (right-section) and then show the image:
function Con1aaRight(div) {
$("#right-section").empty();
show_image("images/netflix.jpg");
}
The problem is the image is showing but not fading in like I would like it to (with d3.ease in the show_image function). I probably should be using JQuery but I would like to incorporate d3. Similar transition/animation ideas welcome. I am building a scrolling webpage tutorial on a data science topic with text on the left and images on the right.
The problem here is understanding what is a D3 transition and how it works.
A D3 transition, as the name implies, transitions from one state, or value, to another state.
That being said, you can, for example, transition...
A position: from x = 10 to x = 60.
A color: from green to blue.
A font size: from 10px to 18px.
An opacity: from 0.2 to 0.9.
A stroke width: from 1px to 5px.
... and several other attributes/styles.
However, you cannot transition this:
non-existence ➔ existence
As Bostock, creator of D3, once said (emphasis mine):
When modifying the DOM, use selections for any changes that cannot be interpolated; only use transitions for animation. For example, it is impossible to interpolate the creation of an element: it either exists or it doesn’t. (source)
Solution: transition the opacity of the image:
var body = d3.select("body");
show_image("http://www.defenders.org/sites/default/files/styles/large/public/tiger-dirk-freder-isp.jpg")
function show_image(source) {
var img = body.append("img").attr("src", source).style("opacity", 0)
img.transition().duration(5000).ease(d3.easeLinear).style("opacity", 1)
}
<script src="https://d3js.org/d3.v4.min.js"></script>
PS: get rid of that jQuery code. You don't need jQuery when using D3. Mixing jQuery and D3 is not only unnecessary but also, in some cases, it will make things silently break.
I am trying to create/invent a new javascript slider object which will work by displaying a base line image:
http://imgur.com/DuVkE.png
then I want to use these 'knobs' to layer on top depending on certain circumstances
http://imgur.com/GKkqx.png
These have already been 'cut up' and will be placed on one of the three black knobs. I have many different colors because I plan to run through them so that the color appears to transform from one, to the other.
So I need to be able to attach an image to the id I received from the user and then manipulate the image later.
My code:
<div id='option1'></div>
<script type="text/javascript">
var slide1 = new slider("option1");
My constructor will look something like this:
function slider(id) {
var obj = document.getElementById(id);
if (!obj) {
var state = -1;
return -1;
}
var state = 0; //blank state
//alert("in");
//alert(document.getElementById(id).className);
//this.addClass("hSliderBack"); INCORRECT SYNTAX!!!
$("#"+id).addClass("hSliderBack"); //this works
}
I fixed the problem with the addClass above, though a little ugly.
My CSS script:
.hSliderBack
{
background-image: url('/Switches/switchLine.png');
background-repeat: no-repeat;
padding-left: 2px; /* width of the image plus a little extra padding */
display: block; /* may not need this, but I've found I do */
}
This is how I can add a picture to my constructor. Still a lot of work to do, but at least it's a start. Any comments are still appreciated as I am very green!!
What you write here:
//obj.innerHTML = "<img src=' this doesn't seem right to me.
is in fact one perfectly reasonable and viable way. You enter into the DOM the <img> node referencing the image you want to display.
However, more common and perhaps more maintainable solution in many cases is to have a CSS style that references a background image, and you enter a <div> into the DOM using the style that causes your image to be displayed.
You should ask yourself, though, is it best to do this without any support from tools. Many of the most popular JavaScript libraries have tools like this built in, or at the very least, have methods that make building this type of code much, much easier.
Of course, if you are doing this to learn the basics of web development before using a framework so you understand what they are doing more thoroughly, more power to you :-)
I am teaching myself web programming. I'm also working on C++. I am having a problem with Javascript.
I need to know how to create an "if statement" based on the location of an image.
I am making a simple game that has a cannon that is moving back and forth. I want the user to press a button that will cause the cannon to stop and fire launching another image toward the target.
I have already created the images and a gif of the image that will travel from the cannon in an arc toward the target.
If the user fires when the cannon is in the correct position the image will hit the target.
Can someone tell me how to create an if statement based on position? Or can someone tell me how to make the cannon stop and make the gif appear?
To move the cannon, read up on the onkeyup() event - it will wait for when a key is released, and do something.
What will it do? Probably change the left position of the cannon somehow. I'd recommend setting the CSS style position:absolute on your cannon, then changing the .left property with Javascript.
For example, here's some Javascript to get you started (untested):
var cannon = document.getElementById("cannonPic");
var leftlim = 200;
document.body.onkeyup = function() {
// Remove 'px' from left position style
leftPosition = cannon.style.left.substring(0, cannon.style.left - 2);
// Stop the cannon?
if (leftPosition >= leftLim) {
return;
}
// Move cannon to new position
cannon.style.left = cannon.style.left.substr(0, cannon + 10);
}
And its companion HTML would look like...
...
<img id='cannonPic' src='cannon.jpg' />
...
<script type='text/javascript' src='cannon.js' />
The HTML could be styled like this:
#cannonPic {
left:0;
position:absolute;
}
To answer your "appear/reappear" sub-question, you can use the .display property, accessed via Javascript:
var cannon = document.getElementById("cannonPic");
function appear() {
cannon.style.display = '';
}
function hide() {
cannon.style.display = 'none';
}
A small word of warning, things traveling in arcs will require some math to translate them in two dimensions, depending on how accurate you want it. A fun exercise though if you like math :)
To get the very first image on your page's x and y position on the screen, for instance, try:
var xpos = document.getElementsByTagName('img')[0].x;
var ypos = document.getElementsByTagName('img')[0].y;
Just to add a little background, the way this is typically done:
You have a main loop that will "run" the game.
Each iteration of the loop, you a) update the positions of in-game objects (cannon, projectiles, and targets in your case) and b) render the resulting objects to the screen.
When you detect a "fire" keypress, you simply set the "speed" of your moving cannon to 0, causing it to "stop".
You can retrieve the object's position using Steve's or sajawikio's approach but your game logic determines (and should know) the position of all objects at all times. It is your game logic that says "draw the projectile at position (x,y)". Your game logic should NOT say "I have a projectile, not sure exactly where it is, HMM, so let's query it's position using Javascript". At least not in this case where you have simple, predictable movement.
I'm trying to change the background image of a button when the mouse is hovered.
with the statement
function testIn ()
{
elem.style.backgroundImage = 'url("image_name_in.png")';
}
function testOut ()
{
elem.style.backgroundImage = 'url("image_name_out.png")';
}
i'm doing this with onMouseOver=testIn() and onMouseOut=testOut().
Here the problem is that, when i hover the mouse. I'm seeing the progress bar (bottom right side) is shown in firefox as if some page is getting loaded
Use :hover pseudo-class and CSS Sprites instead.
You need a few changes in order to pass your object reference:
onMouseOver="testIn(this)"
function testIn (elem)
{
elem.style.backgroundImage = 'url("image_name_in.png")';
}
BTW - convention now uses "onmouseover" (no caps)
You're getting activity in the progress bar because your onmouseover image does NOT load until you call the function.
You could use a sprite combined with :hover CSS for the effect - like #Tomasz mentions.
If you don't want to combine your default and hover image states into a sprite, you may try adding an additional container for the hover image (setting it's default CSS to display:none;) then use JS, or jQuery to swap the display states of the default and hover images on mouseover or hover.
$('myDefaultImage').hover(function() {
$(this).hide();
$('myHoverImage').show();
}, function () {
...the inverse, etc.
});
This will eliminate the progress bar issue because all of your images will be loaded together.
At the same time, this is going to bloat your page size unnecessarily.
I'd really try to go with the :hover CSS and sprite, or reevaluate the importance of what you're trying to accomplish with the image swap (is it really the best solution for your overall project?).