Adding new div into exist div with using onClick() - javascript

Hi im trying to add into new div into exist div by clicking that div and i should do same thing for new div. For example, I have initial div, when i click it i created different div inside it. Then i click new div and i created new div inside it. I hope explanation is understandable =) Here is my code,
<script type="text/javascript" src="js/jquery-1.4.2.min.js">
function run(id){
var id = $(id).attr("id");
document.getElementById(id).onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "50px";
div.style.top = "50px";
div.style.height = "10px";
div.style.width = "10px";
document.getElementById(id).appendChild(div);
};
}
<style>
div.initial {
background-color:white;
width:400px;
height:30px;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class='initial' onclick='run(this)'>
//new div will come here
</div>
</body>
</html>
The problem my javascript isnt working there is nothing when i click div with this code.

Basic idea of what you are after.
function run (){
var div = document.createElement("div"); //create new div
div.addEventListener("click", run); //bind click to new div
this.appendChild(div); //append the new div to clicked div
this.removeEventListener("click", run); //remove the original click event
}
document.getElementById("start").addEventListener("click", run); //bind the initial click event
html, body { height: 100%; }
div {
border: 1px solid black;
width: 90%;
height: 90%;
}
<div id="start"></div>

Here man:http://jsfiddle.net/leojavier/gbuLykdj/2/
<div class='initial'>
//new div will come here
</div>
JS
$('.initial').on('click',function(){
var template = "<div class='newDiv'></div>";
$('.initial').append(template);
})
CSS
div.initial {
background-color:white;
width:400px;
height:auto;
}
.newDiv{
width:20px;
height:20px;
background:blue;
margin:2px;
}

When you call the function run, the parameter passed is an object javascript, not an id of element, you could do this way
var id = $(id).attr("id");

Oh, what an old version of jQuery you're using!! :( You would need to use a delegated click event using the jQuery .live() method. You may not be able to distinguish the new divs because (1) they are absolutely positioned (2) they have the same background color:
$('.initial').live('click', 'div', function(e) {
e.stopPropagation()
$('<div/>').css({
'background-color': 'black',
'position': 'absolute',
'left':'50px',
'top':'50px',
'height': '10px',
'width': '10px'
})
.appendTo( e.target );
});
$('.initial').live('click', 'div', function(e) {
e.stopPropagation();
var randomColor = ['black', 'red', 'yellow', 'blue', 'green', 'orange', 'gray'],
randomN = Math.round( Math.random() * (randomColor.length - 1) );
$('<div/>').css({
'background-color': randomColor[ randomN ],
'left':'25%',
'top':'25%',
'height': '60%',
'width': '15%'
})
.appendTo( e.target );
});
div.initial {
background-color:white;
width:400px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class='initial'>
click here:
</div>

Related

Need to enlarge image at click and then reduce it again by clicking again on external javascript file

This large image is defined in the index.html with a class="small" attribute so it shows as a thumbnail.
<img id="smart_thumbnail" class="small" src="https://image.jpg">
On a separate .js file need to create a function to bring it back to it's normal size and then back to thumbnail by clicking it again. NEED to use if/else. What I am trying to do is to switch between class="" and class="small"
So far I have this but it is not working:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if(thumbnailElement.className = "small";){thumbnailElement.className = "";}
else
{thumbnailElement.className = "small";}
});
});
Any suggestions? Thanks.
Here is something that I made work. It uses JS style properties to change it, not CSS classes. You could copy or reference it:
var imgEl = document.getElementById("Img");
var isBig = false;
imgEl.addEventListener("click", function() {
if (isBig) {
imgEl.style.width = "30px";
imgEl.style.height = "30px";
isBig = false;
} else {
imgEl.style.width = "100px";
imgEl.style.height = "100px";
isBig = true;
}
})
#Img {
border: 1px solid black;
background-color: red;
width: 30px;
height: 30px;
transition: 1s;
}
<div id="Img">
The CSS class switcher isn't working because '=' is not an equal operator, it is an assignment operator. use '==' or '===' for equal operators.
The code above will only run once when the website is initially loaded. To solve this problem, you will need to modify the code so that it is constantly listening for an event.
The code for it should look something similar to the following:
<!DOCTYPE html>
<html>
<head>
<title>Resizing a square with event listeners</title>
<style type="text/css">
.small {
width: 50px;
height: 50px;
}
.large {
width: 100px;
height: 100px;
}
#smart_thumbnail {
background-color: blue;
}
</style>
</head>
<body>
<div id="smart_thumbnail" class="large"></div>
<script>
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if (this.className == "small") {this.className = "large";}
else {this.className = "small";}
});
</script>
</body>
</html>
I also modified the smart_thumbnail so that it has a large/normal size class as well as a small class.

Click on edit jquery

I am a newbie so my question is pretty simple and straight forward.
I have a simple html text. When I click on that html text, the text should change to input field with the value retained and when the user clicks outside the text box, the input text field now should change to html text.
<div class="myText"> Hellow World </div>
Can somebody do this in jquery/Meteor. I am actually building a meteor project
You can do that with the contenteditable attribute
<div class="myText" contenteditable="true"> Hellow World </div>
<!-- Your div is now editable -->
Updated DEMO jsFiddle
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText)
.css({
'position': 'absolute',
top: '0px',
left: '0px',
width: that.width(),
height: that.height(),
opacity: 0.9,
padding: '10px'
});
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
}
that.find('input').remove();
}
});
});
});
In my solution you need to add class="editable" to all editable divs.
You also need to set position: relative to these divs. May be you can update my code and edit the css:
.editable {
position: relative;
}
To correctly align the input inside the div, you need to remove the border or set the .css({}) of the input to left: -1px and top: -1px. The border actually pushes the input 1px left and 1px form the top.
Try this:
$(function() {
$('div.myText').on('click', function() {
var div = $(this);
var tb = div.find('input:text');//get textbox, if exist
if (tb.length) {//text box already exist
div.text(tb.val());//remove text box & put its current value as text to the div
} else {
tb = $('<input>').prop({
'type': 'text',
'value': div.text()//set text box value from div current text
});
div.empty().append(tb);//add new text box
tb.focus();//put text box on focus
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="myText">Hello world</div>
<div class="myText">This is second</div>
Try this:
$(document).click(function() {
$('.myText').html("Hello World");
});
$(".myText").click(function(event) {
$('.myText').html("<input type='text' id='test' value='Hello World'/>");
$('#test').focus();
event.stopPropagation();
});
FIDDLE.
To do it very easily and understandable you can also make two elements instead of changing.
Working fiddle: http://jsfiddle.net/45utpzhx/
It does an onClick event and onBlur.
html
<div>
<span class="myText">Hello World</span>
<input class="myInput" />
</div>
jQuery
$(document).ready(function() {
$(".myText").click(function() {
$(this).hide();
var t = $('.myText').html();
$('.myInput').val(t);
$('.myInput').show();
});
$(".myInput").blur(function() {
$(this).hide();
var t = $('.myInput').val();
$('.myText').html(t);
$('.myText').show();
});
});
Replace the clicked element with an input with value equal to the clicked element's text
$(document).on('click', '.myText', function() {
var that = $(this);
var text = that.text();
that.wrap('<div id="wrp" />');
$('#wrp').html('<input type="text" value="' + text + '" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myText"> Hellow World </div>
You can try this solution :
$('.myText').click(function(){
var m = $(this).text();
$(this).html('');
$('<input/>',{
value : m
}).appendTo(this).focus();
});
$(document).on('blur','input',function(){
var m = $(this).val();
$(this).parent().find('input').remove().end().html(m);
});
working DEMO
$('#text').on('click', function() {
$("#text").hide();
if ($("#text").text()=="Add New text"){
$('#in_text').val("");
}else{
$('#in_text').val($("#text").text());
}
$("#in_text").show();
});
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if($("#text").css('display') == 'none'){
$("#in_text").hide();
if ($("#in_text").val()=="" ){
$('#text').text("Add New text");
$('#text').addClass("asd");
}else{
$('#text').removeClass("asd");
$('#text').text($("#in_text").val());
}
$("#text").show();
}
}
});
#in_text{
display:none;
}
.editable{
width:50%;
}
.asd{
border-bottom : 1px dashed #333;
}
#text{
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editable">
<div id="text" >Text in div</div>
<input type="text" placeholder="Add New Text" id="in_text"/></div>

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Getting mouse click position on image in javascript?

I wrote below code to get co-ordinate of x/y in JAVASCRIPT , it's not working .
I want to create a color picker using this image
when ever some one click on button pick color then it prompts a window with color and button cancel , When user clicked on image than i need to find x/y co-ordinate so that i can specify which color it is .
Problem is that these alerts are not working
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display:none;
position: fixed;
background: #f2f2f2;
border-radius:5px;
z-index: 10;
}
#dialogboxhead{background:white;height:40px;margin:10px;}
#text {float:left; text-align:center;margin:10px; font-size:19px;}
#cancel{float:left;margin:9px;}
#image{
margin-top:0px;
padding:10px;
}
</style>
<script type="text/javascript">
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function position(e){
var offsetl = document.getElementById('image').offsetLeft;
var offsett = document.getElementById('image').offsetTop;
alert(offsetl);
alert(offsett);
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
}
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead">
<p id="text">Select color</p>
<input type="button" onClick="Alert.cancel()" id="cancel" name="Cancel" value="Cancel"/>
</div>
<div>
<img id="image" src="color.png" onClick="position()"/>
</div>
</div>
<button onclick="Alert.render('Hello World');" >pick color </button>
</body>
</html>
I recommend use jQuery and attach click event handler in you image. The event object return in jQuery include two properties, pageX and pageY. This properties contains mouse position relative to the top edge of the document (jQuery Event Object). The code look like this:
$(document).ready(function () {
$('img#image').click(position);
});
function position(e) {
var offsetX = e.pageX,
offsetY = e.page;
}
The sample is in JSFiddle http://jsfiddle.net/zV3dH/.
I hope this help you.
Try this code buddy.. Sure it works
function getClickPos(e) {
return {x:e.clientX,y:e.clientY};
}
Now u can use it like this:
document.querySelector("#img").onclick = function(e) {
var pos= getClickPos(e);
alert(pos.x);
};

Make color on div change depending on where u click

I have a div and a button inside it. I want the div to become, for example, red when you click inside the div, but if you click on the button that's inside, the div should become blue instead.
So just to be clear it is only the div that should shift color, depending on if the click event is in the button or in the div.
My problem is that even when the button is clicked it becomes red because the button is inside the div tag.
This i the code I came up with:
var div_div = document.getElementById("div");
var btn_btn = document.getElementById("btn");
div_div.onclick = function() {
div_div.style.backgroundColor = "red";
}
btn_btn.onclick = function() {
div_div.style.backgroundColor = "blue";
}
<div id="div" style=" width:200px; height:200px; border:2px solid #000; ">
<button id="btn">Button</button>
</div>
The button needs to be inside the div.
for the onclick on the button, make sure you use stopPropagation():
btn_btn.onclick = function(e) {
e.stopPropagation();
div_div.style.backgroundColor = "blue";
}
This stops the event from "bubbling up" to parent elements/handlers.
The event is bubbling.To prevent it use stopPropagation
var div_div = document.getElementById("div");
var btn_btn = document.getElementById("btn");
div_div.onclick = function() {
div_div.style.backgroundColor = "red";
}
btn_btn.onclick = function(e) {
e.stopPropagation()
div_div.style.backgroundColor = "blue";
}
<div id="div" style=" width:200px; height:200px; border:2px solid #000; ">
<button id="btn">Button</button>
</div>

Categories

Resources