I know the title is shit, but I don't know what will be better.
The case is, I create few spans with divs inside on absolute coordinate, according to $(window).width(). When I resize it, I want to rearrange them, so on $(window).resize() I call function to delete the spans, $("span").empty(); and do exactly the same thing, as when I created then. Further more there is a click function, that works fine with the first created spans, and then when I clear then and create exactly the same thing after resize, it doens't work.
Please look at the simplified jsfiddle to understand. First try to click object. Then resize the window and try to click on it.
http://jsfiddle.net/4159v04o/1/
Any ideas why that occurs? Thank you in advance!
It's due to divs being created/erased dynamically. What you need is event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Replace:
$('div').on({click: function() {
With:
$(document).on("click", "div", function() {
Updated fiddle
I have debug the code link and changed the code. there were some code related to name.*. but in name there is only string and you are using style method which is not supporting.
So I removed all the name.* line now it is working fine
var secondstack = [];
var positionTop = 20;
var positionLeft = 20;
document.body.style.background = '#00CCFF';
document.body.style.backgroundSize = "cover";
for(var i = 0; i < 25; i++){
var span = document.createElement("span");
span.style.position = "absolute";
span.style.left = positionLeft + "px";
span.style.top = positionTop + "px";
var div = document.createElement("div");
div.style.width = '105px';
div.style.height = '100px';
div.id = i;
div.style.background = '#00FFCC';
$(div).css({backgroundSize: "cover"});
if((positionLeft + 250) < $(window).width()) positionLeft += 120;
else {
old_Width = positionLeft;
var positionTop = 160 + positionTop;
var positionLeft = 20;
}
span.appendChild(div);
document.body.appendChild(span);
}
DivClick();
var resizeTimer;
$(window).resize(function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
DivClick()
});
function rearrange(){
$("div").empty();
$("span").empty();
secondstack = [];
var positionTop = 20;
var positionLeft = 20;
for(var i = 0; i < 25; i++){
var span = document.createElement("span");
span.style.position = "absolute";
span.style.left = positionLeft + "px";
span.style.top = positionTop + "px";
var div = document.createElement("div");
div.style.width = '105px';
div.style.height = '100px';
div.id = i;
div.style.background = '#00FFCC';
$(div).css({backgroundSize: "cover"});
if((positionLeft + 250) < $(window).width()) positionLeft += 120;
else {
var positionTop = 160 + positionTop;
var positionLeft = 20;
}
span.appendChild(div);
document.body.appendChild(span);
}
}
function DivClick()
{
$('div').on({click: function(){
var el = document.getElementById(this.id);
el.style.border = "3px solid white";
if(!(secondstack.indexOf(this.id) > -1)) secondstack.push(this.id);
else {
var index = secondstack.indexOf(this.id);
el.style.border = "3px solid black";
secondstack.splice(index, 1);
}
}});
}
Just paste and run on same Jsfiddel Example
Related
I need to change style of multiple divs on click of a button that have the same name.I have the button where I create div with image.
This is code for creating the div
function creatContent(e) {
var divMark = document.createElement("div");
divMark.classList = `markers mark`;
var img = $('<img class="comment" src="indeksiraj-1.png" alt="myimage" />');
$(divMark).append(img);
$(marksCanvas).append(divMark);
}
When I create div I can drag that div on browser.Now I need to change the style of div but when I create two div or more when I press the button I change style just of the last div other div stay the same.
This is code for everything:
var xCord;
var yCord;
var xLeft = 0;
var yTop = 0;
function creatContent(e) {
var divMark = document.createElement("div");
divMark.classList = `markers mark`;
var img = $('<img class="comment" src="indeksiraj-1.png" alt="myimage" />');
$(divMark).append(img);
window.onload = addListeners();
function addListeners() {
divMark.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
}
function mouseUp() {
window.removeEventListener("mousemove", divMove, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", divMove, true);
}
function divMove(e) {
xCord = e.pageX;
yCord = e.pageY;
divMark.style.top = yCord + "px";
divMark.style.left = xCord + "px";
}
zoomIn.onclick = function () {
var myImg = document.getElementById("the-canvas");
var currWidth = myImg.clientWidth;
if (currWidth == 1200) return false;
else {
myImg.style.width = currWidth + 100 + "px";
}
xLeft += xCord + 25;
yTop += yCord + 22;
divMark.style.left = xLeft + "px";
divMark.style.top = yTop + "px";
xLeft -= xCord;
yTop -= yCord;
};
zoomOutBtn.onclick = function () {
var myImg = document.getElementById("the-canvas");
var currWidth = myImg.clientWidth;
if (currWidth == 800) return false;
else {
myImg.style.width = currWidth - 100 + "px";
}
xLeft += xCord - 25;
yTop += yCord - 22;
divMark.style.left = xLeft + "px";
divMark.style.top = yTop + "px";
xLeft -= xCord;
yTop -= yCord;
};
}
This is demo https://jsfiddle.net/SutonJ/5gyqexhj/18/
When you are referring to divmark at the movediv function you are referring to the last div you made.
Instead you should refer to a class of that div since all of the divs you made have the same classes if I understand correctly.
So you can use jquery to add the style to the class like so:
$('.markers').css({'top': yCord + "px", 'left': xCord + "px"})
That will add the styling to all the elements that have the class markers.
If you have other elements with that class that you do not want to have those styles then you should add a unique class for those divs you made at divmark.classList.
You should use document.getElementsByClassName('<name of class>')
That way all the divs with the class name will be affected by the event.
The problem is when I enable the eventListener width the scroll eventListener stops working.
var header = document.getElementById("header");
var nav = document.getElemantById("ulArea");
var HaLogo = document.getElementById("logo");
var yPosition = window.scrollTop();
window.addEventListener("scroll" , yScroll);
function yScroll () {
if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
header.style.height = "90px";
logo.style.float = "left";
logo.style.height = "90px";
logo.style.width = "90px";
logo.style.margin = "0px 0px 10px 30px";
ulArea.style.margin = "0px 0px 0px auto";
ulArea.style.float = "none";
} else {
header.style.height = "220px";
logo.style.background = "transparent";
logo.style.float = "none";
logo.style.height = "150px";
logo.style.width = "150px";
logo.style.margin = "0 auto";
ulArea.style.margin = "0 auto";
ulArea.style.float = "none";
}
}
window.addEventListener("width" , headerHeight)
function headerHeight() {
if (document.getElementById("header").width < 990px) {
header.style.height = "100px";
} else {
header.style.height = "220px";
}
}
There are a few problems with your code:
You need to use the resize event (there is no width event).
I think the logo variable isn;t defined, do you mean HaLogo?
ulArea isn't defined.
You need to use the .style.width property of the element (.width doesn't exist).
You need to parse the element's width into an integer with parseInt. If you don't parse it you'll be comparing a string like '50px' to an int 990.
Change < 990px to < 990 (remove the px).
You should end up with if (parseInt(document.getElementById("header").style.width) < 990) { for your if statement and window.addEventListener("resize", headerHeight); for your second event listener.
I think what you are actually looking for is the resize event instead of width:
window.addEventListener('resize', function(event){
// do stuff here
});
My page works in every browser except in IE 10. When I run this page locally in IE 10 there seems to be no problem whatsoever, only when I open the page remotely with IE 10.
The JavaScript is supposed to measure the div with main text and set the height and width of the div's that are off-screen. This is done wrong by IE 10. The width of these div's has to be set because otherwise the will not animate in properly when an item from the menu is clicked.
I did a check on deprecated functions but found none.
I checked the syntax and nothing wrong there. (as far as i can see)
The console in IE does not report any errors.
Anyone any idea as for why locally it works fine in every browser, but remotely the only browser that displays it faulty is IE?
EDIT:
I have removed the function brackets at init so the DOM can initiate, although this did not fix the problem.
script (embedded in the head of the page):
<script src="scripts/jquery-1.10.1.min.js"></script>
<script>
var mainTextDiv = null;
var animate;
var acc = 0;
var currentTab = "home";
var nextTab;
var working = 0;
var bar = 600;
var divW;
function init(){
onWC(currentTab);
document.getElementById(currentTab).style.width = 'auto';
divW = document.getElementById(currentTab).offsetWidth;
document.getElementById("home").style.width = divW + "px";
document.getElementById("profile").style.width = divW + "px";
document.getElementById("news").style.width = divW + "px";
document.getElementById("forums").style.width = divW + "px";
document.getElementById("webshop").style.width = divW + "px";
document.getElementById("status").style.width = divW + "px";
}
function onWC(tab){
var divh = document.getElementById(tab).offsetHeight;
document.getElementById('tabcontainer').style.height = ( divh + 50 ) + "px";
}
function moveDiv(tabName){
if (currentTab == tabName){
return;
}
if (working == 1){
return;
}
working = 1;
nextTab = tabName;
removeDiv();
}
function removeDiv(){
mainTextDiv = document.getElementById(currentTab);
mainTextDiv.style.left = parseInt(mainTextDiv.style.left) + (0.5+acc) + "px";
if (parseInt(mainTextDiv.style.left) > 2000){
mainTextDiv.style.left = 2000 + "px";
onWC(nextTab);
getDiv();
return;
}
acc += 0.15;
animate = setTimeout(removeDiv,10);
}
function getDiv(){
mainTextDiv = document.getElementById(nextTab);
mainTextDiv.style.left = parseInt(mainTextDiv.style.left) - (0.5+acc) + "px";
if (parseInt(mainTextDiv.style.left) <= 0){
mainTextDiv.style.left = 0 + "px";
currentTab = nextTab;
working = 0;
return;
}
acc -= 0.15;
animate = setTimeout(getDiv,15);
}
window.onload = init;
window.onresize = init;
$(function() {
$("#menu ul li a").hover(
function(){
$(this).css("background-color", "#525252");
$(this).css("color", "#FFF");
},
function() {
$(this).css("background-color", "#FFF");
$(this).css("color", "#525252");
}
);
});
</script>
Change window.onresize = init(); to window.onresize = init;
As it stands, the init() is trying to run immediately when the JS file is loaded, which is throwing the error because the DOM hasn't loaded yet.
The script works perfect in FF and IE, but not in Chrome. Could someone help med to locate the problem?
The if statmenst seems not to be runned when they are supposed to, they do nothing when the should.
var top = 285;
var bottom = 650;
var pageheight, maxscroll;
window.onload = function(){
pageheight = document.body.offsetHeight;
maxscroll = pageheight - (bottom+40);
}
window.onscroll = function(){
var element = document.getElementById("guide-menu");
if(window.pageYOffset < top){
element.style.position = "absolute";
element.style.top = "300px";
}
if(window.pageYOffset > top){
element.style.top = "10px";
element.style.position = "fixed";
element.style.marginTop = "0px";
}
if(window.pageYOffset > maxscroll){
element.style.position = "absolute";
element.style.marginTop = (pageheight - bottom - 40) + "px";
}
}
"top" has different meaning in chrome. Just try to rename top variable.
The "top" variable returns the topmost browser window. Chrome is the only major browser not supporting overriding this variable.
Renaming your variable to something like "myTop" works perfectly.
This code works well.
var myTop = 285;
var bottom = 650;
var pageheight, maxscroll;
window.onload = function(){
pageheight = document.body.offsetHeight;
maxscroll = pageheight - (bottom+40);
window.onscroll = function()
{
var element = document.getElementById("guide-menu");
if(window.pageYOffset < myTop)
{
element.style.position = "absolute";
element.style.top = "300px";
}
if(window.pageYOffset > myTop)
{
element.style.top = "10px";
element.style.position = "fixed";
element.style.marginTop = "0px";
}
if(window.pageYOffset > maxscroll)
{
element.style.position = "absolute";
element.style.marginTop = (pageheight - bottom - 40) + "px";
}
}
}
By the way, check that you are puting the right conditions for the IF statements. If you want a menu which scrolls with the webpage, then you have to exchange the two first if conditions.
I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}