Dynamic Div or assigning multiple functions to a Div in CSS/HTML - html

I'm relatively new to Web dev. The question is generic, but I'll pose specific user-cases.
Use-case 1:
I have a div element on a web page. When the page loads the first time, this div runs a small 5 sec animation. What I wish to do is, when this animation ends, I want the same div to contain some other element - it could be an image, a link, another animation etc.
That is, one container - the div - hosting multiple elements on a time-scale. First 5 secs animation , followed by an image or a link.
What Javascript methods will allow me to do so?
Use-case 2:
Again, I have a div element in a page. Now this div element is like a tabbed browser - you click on a different tab to view a different web page. Similarly, I wish to make this a "tabbed" div. As in, when the user hovers the mouse on tab 1, the div would show a video, when hovered over tab 2, it would show another video in the same div - that is, replacing the old video. The tabs can be considered as a fancy looking link.
Or, in the first place, is there an alternative to 'div' to do the things mentioned above?
Thanks,
SMK.

Solution for use case 2 -
This is a slightly lengthy solution but its extremely flexible and can be scaled up to any number of tabs very easily
We will divide the solution into 3 parts - The CSS, HTML and JQuery.
Lets take a look at the CSS part first
<style>
#tab_holder {
width: 350px; !important
}
#tab_holder .tabs {
float: left;
height: 20px;
padding: 5px;
border: 1px solid #eee;
border-bottom: none;
width: 50px;
cursor: pointer;
border-radius: 5px 5px 0 0;
}
#tab_holder .tabs:hover {
background-color: #eee;
}
#tab_holder #content_holder {
width: 400px; !important
margin: 0 0 0 0;
border: 1px solid #000;
padding: 10px;
float: left;
border-radius: 0 5px 5px 5px;
}
.content {
visibility: hidden;
}
</style>
Let us now take a look at the HTML part of this solution
<div id="tab_holder">
<div id="tab1" class="tabs">Video1</div>
<div id="tab2" class="tabs">Video2</div>
<div id="tab3" class="tabs">Video3</div>
<div id="content_holder">
<div id="main_content">Select a tab to see the video..</div>
</div>
</div>
<!-- These are divs in which you put your actual content.
They are always hidden -->
<div id="content1" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/4Z6YUGGlwtA?rel=0" frameborder="0" allowfullscreen></iframe>
< /div>
<div id="content2" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/s13dLaTIHSg?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
<div id="content3" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/I1qHVVbYG8Y?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
You can see that each tab is represented by a div which is using the "tabs" class from the CSS section. If you need to add a new tab, all you have to do is add a new div and give is a new id. For example to add a forth tab, you can say -
<div id="tab4" class="tabs">Video4</div>
It is as simple as that.
Now the thing I like about this approach is that you can place the content to be displayed also in div's, rather that nesting it under jquery. In this case we use the div's with the id content1 content2 content3
This gives you the flexibility to expand as you enter content into the div and use normal markup without getting confused and at ease.
These div's are not visible as we have set their visibility to hidden is CSS.
If you add a new tab div you must also add a new content div.
Now we move onto the JQuery part -
$(document).ready(function (){
/* Add the listeners. */
$("#tab1").mouseover(function (){
switch_content('content1')
});
$("#tab2").mouseover(function (){
switch_content('content2')
});
$("#tab3").mouseover(function (){
switch_content('content3')
});
});
function switch_content(name){
$("#main_content").fadeOut('fast',function (){
$("#main_content").html($("#"+name).html());
$("#main_content").fadeIn('fast');
});
}
The above JQuery function is extremely straight forward. Each tab is attached a action listener which is fired by a mousover event. So if you add another tab with the id=tab4 and its respective content div with the id=content4 then all you have to add in the jQuery is:
$("#tab4").mouseover(function (){
switch_content('content4')
});
So it becomes very easy to expand the code.
You can find a working demo of this on my website demo section
Tips -
Avoid using hover because it creates an annoying user experience due to accidental hovers and it is hard for mobile platforms to emulate this event. Most of them fall back to click. So I suggest use the click event instead.
If you must use, make use of the HTML video tag and pause the video using JS if the user hovers on another tab. This will render a better user experience.

Here is an example for use-case 1.
In your html you need to include the 5 second animation, i persume this is a gif? Although it can be any content. For the sake of this example i will show it as a div.
The html i have used:
<div id="example">
<div id="somecontent"> </div>
<div id="morecontent"> </div>
</div>
The CSS:
#example
{
width:500px;
height:500px;
background-color:#f00;
padding:10px;
}
#somecontent
{
width:200px;
height:200px;
background-color:#fff;
}
#morecontent
{
width:200px;
display:none;
height:200px;
background-color:#000;
}
and the javascript(using jQuery):
setTimeout(function() {
$("#somecontent").fadeOut("slow", function() {
$("#morecontent").fadeIn("slow");
});
}, 5000);​
Have a look at this jsfiddle for it in action - http://jsfiddle.net/fntWZ/
For use case 2 it will be more complicated. Try having a look for some different plugins that could help with this

answer for use-case:1
css :
<style>
#myDiv {
height:0;
width:0;
position:absolute;
border:1px solid red;
}
</style>
script :
$(document).ready(function(){
$("#myDiv").animate({width:"100px", height:"100px"},5000, function(){
var image = new Image();
image.src = "dropdownContainerBottomMiddle.png"; //your image src goes here
$("#myDiv").append(image);
//you can append more content by using setTimeout function
setTimeout(function(){
var anc = "stackoverflow";
$("#myDiv").append(anc);
}, 1000);
});
});
html:
<div id="myDiv"></div>

Related

Scroll to a specific Element Using html

Is there a method in html which makes the webpage scroll to a specific Element using HTML !?
Yes you use this
<div id="google"></div>
But this does not create a smooth scroll just so you know.
You can also add in your CSS
html {
scroll-behavior: smooth;
}
You should mention whether you want it to smoothly scroll or simply jump to an element.
Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id. A side effect is that #theID will be appended to the URL
Go to Title
<div>
<h1 id="scroll">Title</h1>
</div>
You can add CSS effects to the target when the link is clicked with the CSS :target selector.
With some basic JS you can do more, namely the method scrollIntoView(). Your elements don't need an id, though it is still easier, e.g.
function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView();
// will scroll to 4th h3 element
}
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).
<!-- HTML -->
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
Year 2020. Now we have element.scrollIntoView() method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
Text
Here is a pure HTML and CSS method :)
html {
scroll-behavior: smooth;
/*Adds smooth scrolling instead of snapping to element*/
}
#element {
height: 100px;
width: 100%;
background-color: red;
scroll-margin-block-start: 110px;
/*Adds margin to the top of the viewport*/
scroll-margin-block-end: 110pxx;
/*Adds margin to the bottom of the viewport*/
}
#otherElement {
padding-top: 500px;
width: 100%;
}
Link
<div id="otherElement">Content</a>
<div id="element">
Where you want to scroll
</div>
<div id="otherElement">Content</a>
<nav>
1
2
3
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
I got it working by doing this, consider that top-page is the element that you want to scroll to:
document.getElementById("top-page").scrollTo({ behavior: "smooth", top: 0 });
Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.
For example (taken from the W3 specification):
You may read more about this in Section Two.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to Section Two above
for more details.
By using an href attribute inside an anchor tag you can scroll the page to a specific element using a # in front of the elements id name.
Also, here is some jQuery/JS that will accomplish putting variables into a div.
<html>
<body>
Click here to scroll to the myContent section.
<div id="myContent">
...
</div>
<script>
var myClassName = "foo";
$(function() {
$("#myContent").addClass(myClassName);
});
</script>
</body>
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
<style>
#section1 {
height: 600px;
background-color: pink;
}
#section2 {
height: 600px;
background-color: yellow;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
Click Me to Smooth Scroll to Section 2 Below
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
Click Me to Smooth Scroll to Section 1 Above
</div>
</body>
</html>

Set div size of its background image

Is it possible with CSS/HTML to resize some box to match exactly it's background image size? Without using javascript.
For instance let's say I have a simplest div:
<div class="image">TEST</div>
.image {
background-image: url(http://placehold.it/350x150);
width: 350px;
height: 150px;
}
And I would like to resize it to those 350x150 dimensions without hardcoding those values. Also I cannot put any content inside this div.
http://jsfiddle.net/5Dane/
EDIT: I see a lot of answers I already was aware of, thank you for them, but that's not the solution here unfortunately. Below I'm explaining why I need such functionality.
What I'm trying to do is a form with steps (buttons previous and next). In session I hold all the values the user has input but there are some buttons which will add more functionality for the user (like multiple dynamically added rows for data). I'm doing it with jQuery of course, but I want the form to be able to work when there is no java script enabled.
Now to the point - I was trying to find out how to tell the difference which button the user has clicked. The case is all my submit buttons need to be images and the simplest solution <input type="image"/> doesn't send info about the button clicked with POST data. That's why I came to this solution:
<input class="submit_img" type="submit" style="background-image:url(http://placehold.it/108x23); width:108px; height: 23px;" value=" " name="some" />
/* Submit button with image */
input.submit_img {
font-size: 1em;
border-radius: 0px;
box-shadow: rgba(0, 0, 0, 0.15) 0 1px 1px;
border: solid 0px #000000;
cursor: pointer;
}
http://jsfiddle.net/XRvqV/
This way my form will submit all the data AND I will know which button the user clicked. Also the button looks fine, like it should look. I was wondering though if it was possible to make it a little more portable - my buttons all have different widths for different functions. Can someone suggest another approach here?
No, you can't. CSS is not aware of the the image size. You can do it easily with JQuery.
JQuery exmaple
$(function(){
var bg = $("div.image").css('background-image');
bg = bg.replace('url(','').replace(')','');
var newImg = new Image();
newImg.src = bg;
$("div.image").css("width",newImg.width);
$("div.image").css("height",newImg.height);
});
This is a hack and doesn't use background-image (uses an img tag instead), but is the only way I can think of without using JS.
HTML
<div class="container">
<div class="image">
<img src="http://www.pandafix.com/pandafix/images/untitled_1.jpg"/>
</div>
<div class="content">
some text
<br/>
some more text
<br/><br/><br/><br/>
text text text
</div>
</div>
CSS
.container {
position: relative;
}
.content {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
color: red;
}
Basically, you allow an img tag to determine the height and width of a container. Then, overlay whatever content you want on top of the image (I'm assuming you want to put something on top).
jsFiddle
i would suggest you a alternative way to solve your problem. if you use bootstrap you can involve a div to make resizable image.
<div class="img-responsive">
<img src="test.jpg" width='xxx' height='yyy' alt='test'>
</div>
You can't do that using just HTML. But you can do this using HTML!
You should try this:
background-size: values;
This way, you will resize the background-image to the size of the container!
You can't do it directly.
The only solution it would be fetching the BG of the DIV element and attach new DOM img element to the DOM node, afterwards you could use the info of the image to add the proper with and height..
if you are willing to use jquery you can do this.
$(function(){
$('.image').each(function(index,element){
var _t = $(this);
_t.data("LinkedImg","LinkedImage"+index);
$('body').append(
$('<img />',{
id:"LinkedImage"+index,
src:_t.css('background-image')
}).hide());
});
$('document').on('load',function(){
$('.image').each(function(index,element){
var _t = $(this);
var _tmp_img = $('#'+ _t.data("LinkedImg"));
_t.css({
width:_tmp_img.width(),
height: _tmp_img.height()
});
});
});
})

CSS :target random #keyword, do something with same div

I have some links, and each of these have a unique href.
lets say link one have href="#first".
and link two have href="#second".
What would then be the CSS to do something with a div? (with the ID box)
I have tried lots of things like:
#first:target #box{
something..
}
#second:target #box{
something else..
}
#linkOne:hover #box{ width:200px; }
This changes the size of #box by hovering #linkOne I want the same to happen with :target, like change the size of #box by clicking the link
If you want to select the currently targeted element, you can simply do :target
html
first link
second link
<div id="first">first div</div>
<div id="second">second div</div>
css
:target {
border: 1px solid red;
}
The div with the corresponding id of the link clicked will have a red border.
http://jsfiddle.net/wk3rR/2/
UPDATE
Judging by your comment, it appears you want to manipulate the same box with different current targets, which won't be straight-forward, but can be done if you nest the <div>s with the IDs and then your original css should work:
first link
second link
<div id="first">
<div id="second">
<div class="box">box</div>
</div>
</div>
css
#first:target .box {
border: 1px solid red;
}
#second:target .box {
border: 1px solid yellow;
}
http://jsfiddle.net/wk3rR/3/
If I am not wrong, you are looking for something like the below. This will set the height of the currently targeted element to 20px. Transition effect will also be applied.
HTML:
<a href='#first'>First</a>
<a href='#second'>Second</a>
<div id='first'>This is first div</div>
<div id='second'>This is second div</div>
CSS:
#first, #second {
height: 0px;
overflow: hidden;
transition: height 1s ease-in;
}
#first:target {
height: 20px;
}
#second:target {
height: 20px;
}
Demo Fiddle
EDIT: I know you haven't tagged jQuery/JavaScript and was looking for a CSS solution. But if you have many such links and are ok to have a JS based solution, you can try the below.
This script has a mapping between the id of the link that is clicked and the height that the box is supposed to have when the link is clicked. Based on it, the #box element's height is modified. Transitions will also work as can be seen in this fiddle.
window.onload = function () {
document.getElementsByTagName('body')[0].onclick = function(e){
var box = document.getElementById('box');
var heights = { first: '20px', second: '40px', third: '30px' };
if(e.target.id)
box.style.height = heights[e.target.id];
};
}
I think you need the use of javascript if you want manipulate DOM. You have to remember CSS is only for style the page, not for making actions with the elements.

Use Only CSS to Alter Various Elements

I have a page with a left sidebar that I want to be able to toggle on or off based on whether or not the user clicks it. Unfortunately entering JavaScript code on this website has been disabled and I only have access to CSS.
The left sidebar has
its main div (parentBlock)
a div for the show/hide, (toggleBlock)
a div for the logo, (div1)
a div for the navbar, and (div2)
a div for social icons (div2)
When the user clicks on "Show / Hide" I want to:
Hide (display:none) the logo, navbar, and social div's, and
Set the height of the main div to something smaller (say 30px).
Is there any way to do this in CSS?
<div class="parentBlock">
<div class="toggleBlock">Show / Hide</div>
<div class="divBlah">div1</div>
<div class="divBlah">div2</div>
<div class="divBlah">div3</div>
</div>
Then if the user clicks "Show / Hide" again, it will unhide the div's and set the height back to filling the screen.
Is this possible?
I found some code that would work if the "Show / Hide" button was in "parentBlock" but it didn't work if it was within "toggleBlock" (and I have to have the Show/Hide button in toggleBlock)
(http://tympanus.net/codrops/2012/12/17/css-click-events/)
I realize onClick events require JavaScript. Those are not possible since I can't use JavaScript :( Some people try to get around it by using either :active or creating checkboxes and having the checkbox:clicked value load the action ... but it only works with certain relations that I can't seem to nail down.
Unfortunately I cannot alter the ultimate structure of "toggleBlock", div1, div2, and div3 ... only what's in them and their CSS. Also making it even more difficult is that the website randomly generates ID="" each time the page loads so the TARGET method isn't possible. Also, the 3 div's (div1 thru div3) have the same class name. I'm beginning to think it's impossible :(
(For reference, I'm trying to use the tools on the New SmugMug and they're rather restrictive)
Here is a CSS only solution using target
DEMO http://jsfiddle.net/kevinPHPkevin/r4AQd/
.button {
display: block;
width:60px;
background: red;
z-index:1;
}
#element {
display: none;
background:#fff;
margin-top:-20px;
z-index:2;
}
#element:target {
display: block;
}
#show:target {
display: block;
}
#hide {
background: #000;
color: #fff;
}
As Joum has pointed out this is not possible to do via click events but using hover on siblings you might be able to achieve a similar effect. for example try adding this css:
div.toggleBlock { display: block; }
div.toggleBlock ~ div { display: none; }
div.toggleBlock:hover ~ div { display: block; }
for more information see this: http://css-tricks.com/child-and-sibling-selectors/

Is it possible to manually scroll a JPG inside a div with 'little hand' cursor?

Is it possible to manually scroll a JPG inside a div with 'little hand' cursor by grabbing and draging the actual image?
Just when for example you have long horizontal bitmap and want to show it in small window so people scroll like in photo editors when you zoom in.
You need some JavaScript magic to do this. Check this out: http://jsfiddle.net/bCuGM/.
<style type="text/css">
#container {
width: 400px;
height: 400px;
overflow: hidden;
cursor: pointer;
}
#draggable {
width: 1024px;
height: 819px;
}
</style>
<div id="container">
<div id="draggable">
<img src="http://farm3.staticflickr.com/2593/3884464511_a77144821e_b.jpg">
</div>
</div>
<script>
$("#draggable").draggable();
</script>
You can do it by using javascript and a bit of css.
On your image add a css rule with :
cursor: pointer;
using javascript, add mousedown, mousemove and mouseup events on your image. Then use javascript to change the scroll on the parent div