Change Div Size dynamically - javascript

In my code, I've got 4 divs aligned inline.
What I want is, on clicking any div, it resizes to fill the space of all 4 divs (width:1000px)
and hides the other divs.
And on reclicking the div, it'll resize to the original dimensions.
This is what i've done till now.
<div class="gallery-image-replenish" id="bloc2" onclick="document.getElementById('bloc2').style.width = '980px'">
</div>
As of now, on click this resizes the div below the other divs. I know there's a method to hide the other divs, but I don't know how to do that.

With this kind of HTML:
<div class="gallery-image-replenish" id="bloc1"></div>
<div class="gallery-image-replenish" id="bloc2"></div>
<div class="gallery-image-replenish" id="bloc3"></div>
<div class="gallery-image-replenish" id="bloc4"></div>
you can use this kind of JS:
var handler = function(e){
e.target.style.width = "1000px";
for (j = divs.length; j--; ) {
if (divs[j].id != e.target.id) {
divs[j].style.display = "none";
}
}
}
var divs = document.getElementsByClassName('gallery-image-replenish'); //array of divs
var div;
for (i = divs.length; i--; ) {
div = divs[i];
div.addEventListener('click', handler);
}

Is it possible to use jQuery (jquery.com) on your project?
Because it would save a lot of code (and make it more readable!).
It would look like this (not tested, but probably works :P):
<div id="bloc1" class="gallery-image-replenish">1</div>
<div id="bloc2" class="gallery-image-replenish">2</div>
<div id="bloc3" class="gallery-image-replenish">3</div>
<div id="bloc4" class="gallery-image-replenish">4</div>
<script>
jQuery(document).ready(function(){
var galleryElements = $('.gallery-image-replenish');
galleryElements.click(function(){
var clickedElement = $(this);
if (clickedElement.hasClass('expanded')) { // if it has the class expanded, remove it (and show other elements again)
clickedElement.removeClass('expanded');
galleryElements.show();
} else { // if it has not got the expanded css class hide other and add class to expanded
galleryElements.not(clickedElement).hide(); // hide every other div
$(this).addClass('expanded'); // add stylesheet class for the new bigger width
}
});
});
</script>

The pure javascript way to hide an element is:
document.getElementById('otherdiv1').style.display = 'none';

Following is a solution which uses a common javascript function to perform what you want:-
<div class="gallery-image-replenish" id="bloc1" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc2" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc3" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc4" onclick="manageDivs(this.id)"> </div>
<script type="text/javascript">
function manageDivs(divId)
{
document.getElementById(divId).style.width = '980px'";
//to hide rest of the divs
for(i=1;i<=4;i++)
{
if(divId!='bloc'+i)
document.getElementById('bloc'+i).style.display = 'none';
}
}
</script>

This is a simple exemple ,
var activ = false;
$('.aligned').live('click',function(){
if(!$(this).hasClass('actif')) {
$('.aligned').css('width','0');
$('.aligned').removeClass('actif');
$(this).css('width','1000px');
$(this).addClass('actif');
} else {
$('.aligned').css('width','250px');
}
});
you can use jQuery animate for more visual effect

Related

angular show and hide function

I have created a show and function using Angular. At the moment i have the basics working. When the user hovers over tile the class is added and removed.
<article class="col-sm-6" ng-mouseenter="showHiddenTile()" ng-mouseleave="hideHiddenTile()">
<div class="grid-block--img">
<img src="/assets/homepage/home-tile5.png">
<div class="grid-headings">
<h2>a new<br/>home for<br/>whiskey</h2>
<p><span class="heading--bold">WORK.</b><span> Food and Beverage Design<
</div>
<div class="grid-block-hidden" ng-class="{isVisble: tileBlock}">My overlay</div>
</div>
</article>
I want to use this show and hide function multiple times throughout the site. At the moment when I hover over one of the elements it adds the isActive class to all elements instead of individually.
Angular code
// SHOW AND HIDE FUNCTION
$scope.showHiddenTile = function() {
$scope.tileBlock = true;
}
$scope.hideHiddenTile = function() {
$scope.tileBlock = false;
}
How can I target the isVisble class individually?
Have an array
$scope.array = [];
push it to array when mouseenter event
function showMethod(element){
$scope.array.push(element);
}
slice it from array when mouseleave event
function hideMethod(element){
$scope.array.slice($scope.array.indexOf(element),1);
}
use this condition in ng-class
ng-class="array['blockName'] != -1"
You could do something like:
<article class="col-sm-6" ng-mouseenter="showHiddenTile('block-id')" ng-mouseleave="hideHiddenTile('block-id')">
And:
$scope.showHiddenTile = function(blockId) {
$scope.tileBlock[blockId] = true;
}
$scope.hideHiddenTile = function(blockId) {
$scope.tileBlock[blockId] = false;
}
$scope.isShowTitle = function(blockId) {
return $scope.tileBlock[blockId];
}
And:
<div class="grid-block-hidden" ng-class="{isVisble: isShowTitle('block-id'}">My overlay</div>
And then have a unique block-id per article.
why not have 2 styles
.grid-block-hidden{
//style when mouse is not on
}
grid-block-hidden:hover{
//style on hover
//isVisble class
}

Changing html tag structure on window resizing

I would like to rebuild an html tag structure to a new one on resizing the browser window. Have anyone an idea how can I get from the first structure to the second structure. I need this for an responsive personal project. Maybe with an JavaScript resize Event, I don't know...
<div class="wrapper">
<div class="slide">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="slide">
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div class="wrapper">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
You could listen to the resize event on the window and then restructure your HTML when the window is below a certain size. Moving elements from the first structure to the second isn't a big problem, however the challenge lies in reverting that again. How will you know which of the .item's belonged to which .slide?
One way to do this is to keep track of the parent for each .item in a separate data- attribute when you make the list:
function makeList() {
var $slides = $('.slide'),
$items = $();
// For each slide set a data-attribute on all its child .item's
$slides.each(function(i) {
var $item = $(this).children('.item');
$item.attr('data-slide', i+1);
$items = $items.add($item);
});
// Append all items directly to the wrapper
$('.wrapper').html($items).attr('data-structure', 'list');
}
I set a data attribute to the .wrapper so we know that it's already converted to a list. Otherwise on every resize this would be fired, you only want it once (until it resizes back to where you want the slides).
When you want the slide again, loop through all the .items and keep a list of slide number's. For each new data-slide number you encounter make a new slide and add that to the total list;
function makeSlides() {
var $slides = $(),
slideNumbers = [],
$currentSlide = $();
$('.item[data-slide]').each(function() {
var $item = $(this),
slideNumber = $item.attr('data-slide');
// if the slide number wasn't in the array yet push the current slide into $slides and create a new one
if(slideNumbers.indexOf(slideNumber) < 0) {
$slides = $slides.add($currentSlide);
$currentSlide = $('<div class="slide" />');
slideNumbers.push(slideNumber);
}
$currentSlide.append($item);
});
// add the last currentSlide
$slides = $slides.add($currentSlide);
// place all slides in the wrapper
$('.wrapper').html($slides).attr('data-structure', 'slides');
}
Then finally you bind the resize event and fire these functions when needed:
$(window).resize(function(e) {
var currentStructure = $('.wrapper').attr('data-structure');
if(window.innerWidth < 600) {
if( currentStructure !== 'list') {
makeList();
}
} else {
if( currentStructure !== 'slides') {
makeSlides();
}
}
});
jsFiddle demo: http://jsfiddle.net/gktLnw31/3/
I do think this could be a bit more efficient, but this is just a proof of concept. Hopefully it'll give you some insights.
I would better take a look at foundation since it already includes the responsive design by default instead of trying to change it dynamically by code

Change content of a div which has a non unique class

Want to change HTML content of a div which has a certain class but problem is there are several others and they get change too.
<div class="x"></div>
<div id="y"><div class"x">Change this</div></div>
<div class="x"></div>
I'm trying
function ReplaceContentInContainer(matchClass,content)
{
var elems = document.getElementsByTagName('*'),i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1)
{
elems[i].innerHTML = content;
}
}
}
window.onload = function ()
{
ReplaceContentInContainer("x","Success"}
but as you can guess it changes every class"x", so how can I limit this only to the class="x" which is nested in a div with id="y"?
Use jQuery
$("#y .x").html("changed it");
That is all

Close all divs with same class at once when one ot them is ckicked (except the one we click on)

Project: Close all other divs with same class at once when we click on one, except of course the one we click on.
I found here 2 parts of code that I think could do it, but I do not know how to put it together.
To get my elements with same class (MaxPackage) - I am aware not all browser handle the getElement...
var elements = document.getElementsByClassName("MaxPackage");
for (var i = 0, len = elements.length; i < len; i++) {
// elements[i].style ... <-- I do not know what this means
}
And the part I found (as is) that could do the toggle part I think:
var prevId;
function toggle_visibility(id) {
if(prevId && id !== prevId){
$("#"+prevId).slideToggle("slow");
}
var e = document.getElementById(id);
$(e).slideToggle("slow");
prevId = id;
}
Thank you for your help, I am not a programmer, so please do not be afraid to explain :) Then I will need to know how to trigger it (onload or add function in element)?
Edited: I got a very simple solution:
$('div.MaxPackage').click(function(){
$('div.MaxPackage').hide();
$(this).show();
});
Try this, which is a very simple vanilla javascript way to get what you want
<div class="MaxPackage" onclick="closeThem(event)">one</div>
<div class="MaxPackage" onclick="closeThem(event)">two</div>
<div class="MaxPackage" onclick="closeThem(event)">three</div>
<div class="MaxPackage" onclick="closeThem(event)">four</div>
<script type="text/javascript">
function closeThem(e) {
var divs = document.getElementsByClassName('MaxPackage');
for (var i=0; i < divs.length; i++) {
if (e.target !== divs[i]) {
divs[i].style.display = 'none';
}
}
}
</script>
In jQuery the following will work
function addSingleSelect(classToSelect) { // Pass in the name of the class
$('.' + classToSelect).click(
function(event) {
var selected = event.target; // Get Selected Click Target
$('.' + classToSelect).css('display', 'none'); // Hide EVERYTHING
$(selected).css('display','') // Show the selected item
}
);
}
Assume you had
<div id="1" class="MaxPackage">Max 1</div>
<div id="2" class="MaxPackage">Max 2</div>
<div id="3" class="MaxPackage">Max 3</div>
you could call
addSingleSelect('MaxPackage');
and do the same for anything else as well with a different class
HTML
<div id="4" class="MinPackage">Min 4</div>
<div id="5" class="MinPackage">Min 5</div>
<div id="6" class="MinPackage">Min 6</div>
JS
addSingleSelect('MinPackage');

When one is clicked, disable the other

So I have a mini slide menu in my website there is a menu you can choose what you want to read. There are points to click, when u clicked it the point get a red background.
But there is a problem.
When i click one point and then an other point the first clicked point have to lose his background.
Here is my HTML:
<div id="slide_button" onClick="clicked(this);"><dir class="button_1"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_2"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_3"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_4"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_5"></dir></div>
Here is my JS:
function clicked(slide_button) {
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
HERE IS AN EXAMPLE ON FIDDLE.
My "QUESTION IS" what i have to do to solve that?
What should I pay attention?
First you need to fix your HTML becaue your id values aren't unique. In fact, you don't even need id values, so you should use "slide_button" as a class. You can then use it to select all the buttons:
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
The CSS needs to be changed now so "slide_button" is a class selector, instead of an id selector:
.slide_button {
display: inline-block;
}
As for clearing the background, clear all of them before coloring the selected one red:
function clicked(slide_button) {
var buttons = document.getElementsByClassName('slide_button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].getElementsByTagName('dir')[0].style.backgroundColor = '';
}
slide_button.getElementsByTagName('dir')[0].style.backgroundColor = 'red';
}
jsfiddle
This uses just JavaScript with no JQuery, but if you are using JQuery, you might as well use it here. The code is a lot shorter and easier to follow.
Here's a JQuery version:
$(function() {
$('.slide_button').click(function() {
var $button = $(this);
$button.children(':first').css({ backgroundColor: 'red' });
$button.siblings().children(':first').css({ backgroundColor: '' });
});
});
Note: This registers a click-handler, so you can get rid of the "onclick" attirbutes.
jsfiddle
You have to select all other points and set their background to none.
Or remeber which point is selected and on select another just remove background on last and remeber current point, then set its background to red.
See fiddle: http://fiddle.jshell.net/399Dm/5/
At first id should be unique per element.
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
Second, you should store reference of clicked element if you want later remove background color, and instead of inline event handlers or binding all elements would be better if you use event delegation.
Demonstration
(function () {
"use strict";
// getting parent node of divs, due to bind click event. then
var ele = document.querySelector(".slide_button").parentNode,
prev = null; // store previous clicked element
ele.addEventListener("click", clickHandler); // event handler.
function clickHandler(e) {
var t = e.target; // get target of clicked element
// filter by target node name and class. edit: removed class checking
if (t.nodeName.toLowerCase() === "dir") {
// checking value of prev !== null and it's not same element.
if (prev && prev !== t) {
prev.style.backgroundColor = "";
}
prev = t; // store clicked element
t.style.backgroundColor = "red";
}
}
}());
I have fixed the fiddle so that it works hopefully as you plan.
http://jsfiddle.net/399Dm/8/ There you go!
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
function clear(element, index, array) {
element.getElementsByTagName("dir")[0].style.backgroundColor="";
}
function clicked(slide_button) {
forEach(document.getElementsByClassName("slide_button"), clear);
//.style.backgroundColor="";
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
I had a slightly different method than #atlavis but a similar result.
http://fiddle.jshell.net/2AGJQ/
JSFIDDLE DEMO
jQuery
$('.slide_button').click(function(){
$('.slide_button dir').css("background-color", "inherit");
$(this).find('dir').css("background-color", "red");
});
HTML - Your markup is invalid because you have duplicate ids. Make them classes as below instead.
<div class="slide_button" >
<dir class="button_1"></dir>
</div>
<div class="slide_button">
<dir class="button_2"></dir>
</div>
<div class="slide_button">
<dir class="button_3"></dir>
</div>
<div class="slide_button">
<dir class="button_4"></dir>
</div>
<div class="slide_button">
<dir class="button_5"></dir>
</div>
CSS change
.slide_button {
display: inline-block;
}
If you can look at the following jsfiddle, I used jQuery to get what you want.

Categories