div is not displayed on click of image - javascript

I have an image at the top right corner of a page. on click of the image i have to display a div that looks like a table with many rows. The div has to be positioned exactly below the image.I have tried the below code snippet.
<div><img align=right src="Test.png" /></div>
sample code snippet for test function
Test(){
var hNode = document.createElement('div');
hNode.style.display = "block";
hNode.style.overflow="hidden";enter code here
hNode.style.position = "absolute";
hNode.style.width = "400px";
hNode.style.height = "30px";
hNode.style.border = "1px solid #666666";
hNode .appendChild(document.createTextNode("Test"));
}
But the div does not show up.
What is wrong with this snippet? Any help would be great..

Maybe use an onclick="Test()" in your <a> tag

first : change a to link
second : in function implementation add function keyword before Test()

<div onclick="Test()"><img align=right src="Test.png" /></div>
may help.

function Test(){
var hNode = document.createElement('div');
hNode.style.display = "block";
hNode.style.overflow ="hidden";
hNode.style.position = "absolute";
hNode.style.width = "400px";
hNode.style.height = "30px";
hNode.style.border = "1px solid #666666";
var t = document.createTextNode("Test");
hNode.appendChild(t)
document.body.appendChild(hNode);
}
while all the other answers are addressing problems with your code the answer as to why it doesn't appear is
you aren't actually appending the newly created div to document.body so although it exists it isn't part of the dom.
you can call this function using any of the methods described in other answers; i prefer something along the lines of
my link
to direct users without javascript enabled to a page telling them why javascript is necessary for that particular link.

Related

Javascript: Display clickable images at the end of each paragraph

$(document).ready(function(){
function createPopup(event){
$('<div class="popup"><img src="mysrc.jpg" img style="opacity=0.5; width:50px; height:50px;"></img></div>').appendTo('body');
positionPopup(event);
};
function positionPopup(event){
var tPosX = 950;
var tPosY = event.clientY+25;
$('div.popup').css({'position': 'absolute', 'top': tPosY, 'left':tPosX});
$('#test').attr('ydown', parseInt(tPosY)+ parseInt(add));
};
var elements = document.getElementsByTagName('cposs');
for(var i = 0; i < elements.length; i++){
var imagetest = document.createElement("img");
imagetest.src = "mysrc.jpg";
elements[i].onmouseover = function(){
this.style.background = 'Green';
createPopup(event);
}
elements[i].onmouseout = function(){
this.style.background = '';
}
var ycoor= $('#test').attr('ydown');
$( "#test" ).append( "<a href=http://www.google.com><img src='mysrc.jpg'</img></a>" );
}
});
</script>
<div id="test" ydown="<?php echo $ydown; ?>" xdown="<?php echo $xdown; ?>">
There is then multiple paragraphs with <cposs></cposs> tags and this allows the text to be highlighted when the mouse is hovered over and creates a popup image to the right of the paragraph. I also have for each counted <cposs></cposs> an image that is displayed in the test div.
There is a couple things I was hoping I would be able to accomplish:
On page load, I would like an image to be displayed at the end of each <cposs></cposs> text. Instead of fixed coordinates.
I would like these images to execute a function when clicked on.(Tried adding the "onclick" attribute but said the function was not defined)
Eventually, I would like the clickable images to cause the text between the cposs tags to highlight. Similar to what I have now, but instead of mouse over, its a click event.
EDIT:
I have tried to add an onclick attribute to the appended image but once the image is clicked, says the function is not defined.
I am unsure on how to get the coordinates of the cposs tags. I am confused on if I am able to use offset and or position function in javascript. I have attempted to use both and have not succeeded.
I guess all I really need to know if how to get the end coordinates of the cposs tags and how to give each displayed image a clickable function
I am a big fan of jsfiddle!
Any sort of help is greatly appreciated!
Thanks in advance.
Here's a jsFiddle example: https://jsfiddle.net/sn625r3z/14/
To make freshly added elements clickable you should be using jQuery's ".on" function and pass an event to it. Something like this:
$('img.new-image').on('click', function(){
$(this).parent().css({background: 'green'});
});
In the jsFiddle example I positioned images with CSS. But if you want to get the coordinates to position the image at the end of the block I would do it like this:
$('cposs').each(function(){
var el = $(this);
var width = el.width();
var height = el.height();
var newElement = $('<img class="new-image" src="'+imagetest.src+'" />');
el.append(newElement);
newElement.css({top: height+"px", left: width+"px"});
});
Hope this helps.

How can I add a button within an innerHTML section of a HTML div?

I pretty new at JavaScript & JQuery, more knowledgeable at html & css but I have something I've been working on for days and banging my head to the desk and can't figure it out. Maybe someone could help me, any hint, suggestion would be greatly appreciated!!
I have the following HTML:
<div id="projects" class="fluid">
<button onClick="myFunction2()" class="viewprojectsclose">Close</button>
<button onclick="myFunction()" class="viewprojects">View Projects</button>
<div id="projectsimg">
</div>
<div id="projectstxt">
</div>
</div>
with the following JavaScript and JQuery:
function myFunction() {
document.getElementById("projectstxt").innerHTML = 'some text some text some text';
document.getElementById("projectstxt").style.borderBottom = "thin solid #000" ;
document.getElementById("projectstxt").style.display = "block";
document.getElementById("projectstxt").style.paddingBottom ="10px";
document.getElementById("projectsimg").style.padding = "100px" ;
document.getElementById("projectsimg").style.background = "url('../Assets/img/services/image1.png')" ;
document.getElementById("projectsimg").style.backgroundRepeat = "no-repeat";
document.getElementById("projectsimg").style.backgroundSize = "20%";
document.getElementById("projectsimg").style.display = "block";
document.getElementById("projectsimg").style.transition = "all 0.5s ease-in-out";
document.getElementById("projectsimg").style.backgroundOrigin = "border-box";
document.getElementById("projectsimg").style.marginTop = "5%";
;}
function myFunction2() {
document.getElementById("projectstxt").style.display = "none";
document.getElementById("projectsimg").style.display = "none";
;}
$(document).ready(function()
{
$(".viewprojects").click(function(){
$("#projects").animate({
height:"300px"
});
});
$(".viewprojectsclose").click(function(){
$("#projects").animate({
height:"80px"
});
});
});
Basically we have 2 buttons(OPEN and CLOSE). First opens the image and text DIV and 2nd one closes. What I'm trying to do is add another button below the image(within the div) that will redirect you to a specific page. I can add a regular button in the image DIV in HTML but when it loads the page that button appears on it by default though it should appear only when clicking on the 1st button( and opens the innerHTML). This means that I have to add it somehow in JS. If I press close and reset the div, then the button appears as it should, only when clicking on the 1st OPEN button. I have no idea what is the JS script to prevent from loading the button at first and load it only when I click on the 1st button within the JS.
Any help would be divine!! Thank you in advance!
Yes, there is a conflict because you're over-riding the click handler for your buttons in javascript and jquery. You don't have to do that at all. You should in MHO stick to Jquery and just add the appropriate DOM changes in the click handlers like so:
$(document).ready(function()
{
$(".viewprojects").click(function(){
//Animate first
$("#projects").animate({
height:"300px"
});
//Update DOM
document.getElementById("projectstxt").innerHTML = 'some text some text some text';
document.getElementById("projectstxt").style.borderBottom = "thin solid #000" ;
document.getElementById("projectstxt").style.display = "block";
document.getElementById("projectstxt").style.paddingBottom ="10px";
document.getElementById("projectsimg").style.padding = "100px" ;
document.getElementById("projectsimg").style.background = "url('../Assets/img/services/image1.png')" ;
document.getElementById("projectsimg").style.backgroundRepeat = "no-repeat";
document.getElementById("projectsimg").style.backgroundSize = "20%";
document.getElementById("projectsimg").style.display = "block";
document.getElementById("projectsimg").style.transition = "all 0.5s ease-in-out";
document.getElementById("projectsimg").style.backgroundOrigin = "border-box";
document.getElementById("projectsimg").style.marginTop = "5%";
});
$(".viewprojectsclose").click(function(){
document.getElementById("projectstxt").style.display = "none";
document.getElementById("projectsimg").style.display = "none";
//Animate the div
$("#projects").animate({
height:"80px"
});
});
});
Now, I have just restructured the code that you posted in the question to give you an understanding how to fix it. The code is NOT sanitized and the syntax should be appropriately changed according to Jquery specs for simplicity and ease. It's a simple exercise that you can do on your own.
PS: I have updated the fiddle to incorporate the changes that I just mentioned and it seems to be working fine. Again, I know the Jquery syntax is not appropriate but it's deliberate. Anyway, I hope it gets you started in the right direction. Also, when using javascript and Jquery, stick to one either pure javascript or jquery as you can achieve almost all the functionality that you require her in jquery and it is more versatile and easy to use.

How to Expand / Collapse a section of a Web Site and also change the image using JavaScript

EDIT #1
Thanks to the 2 users who responded, their solutions worked great! Something I forgot to mention in the original post was, Is there any way to adjust the user's view so that when the expanded section is collapses by the user, their "view" (or the actual web page) can adjust up to an anchored spot?
ORIGINAL POST
I've got a section of a website that I want to first be collapsed and not able to be viewed by the user. Then, when they hit an arrow on the screen, the hidden content will then display AND the image needs to change from a "down" arrow to an "up" arrow.
I'm able to do this with the below code right now but I have to have two arrows. Can anyone help so that I only have one arrow on screen and it changes based on when the user clicks on it? I'd also like this to be able to be done an infinite amount of times by the user (ie if the user clicks the "down" arrow, the section expands and the arrow changes to an "up" arrow but then when the user hits that "up" arrow the section collapses and the arrow changes back to a "down" arrow. Possible?
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl(h) {
var tbl = document.getElementById('tbl');
tbl.style.display = h;
}
// -->
</script>
<br>
<img src="up_arrow.png">
<img src="down_arrow.png">
Thanks for any help!
I have added your code and created a jsfiddle for you...
changed code:-
function sizeTbl(h) {
var tbl = document.getElementById('container');
tbl.style.display = h;
if (h == "block") {
document.getElementById('down').style.display = 'none';
document.getElementById('up').style.display = 'block';
} else {
document.getElementById('up').style.display = 'none';
document.getElementById('down').style.display = 'block';
}
}
working example:-
click to see example:-http://jsfiddle.net/XUjAH/1089/
thanks
I've taken out the parameter from your sizeTbl method
Then I'm getting the src property of the image (note I've given it an ID). Depending on the src we can show/hide the table and change the image property
Here's a jsFiddle
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.src === 'down_arrow.png'){
tbl.style.display = 'block';
icon.src = 'up_arrow.png';
}
else {
tbl.style.display = 'none';
icon.src = 'down_arrow.png';
}
}
// -->
</script>
<br>
<img src="down_arrow.png" id="toggle-table">
You've added some extra requirements to your question. You've tagged jQuery and this is the easiest solution for this scenario.
Remove the javascript:sizeTbl() from your <anchor> tag. This is known as inline JS and isn't recommended because it means you are mixing your presentation code with your business logic.
You make the <anchor> tag act like a normal anchor tag and attach a click event in the document's ready event.
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.innerText === 'show') {
tbl.style.display = 'block';
icon.innerText = 'hide';
} else {
tbl.style.display = 'none';
icon.innerText = 'show';
}
}
$(document).ready(function(){
$('#sizeTbl').on('click', sizeTbl);
});
I've created a new jsFiddle that demonstrates this.
Notes:
You need to be using jQuery for this to work
Note that I've given the <anchor> tag an ID. This is so that I can locate it in code
If you have any other comments, the etiquette on SO is to ask new questions. The answers get too long and complicated otherwise

Javascript hiding and showing dynamic content of a div

Currently I hide and show the content of a div like this:
var header = null;
var content = null;
var mainHolder = null;
var expandCollapseBtn = null;
var heightValue = 0;
header = document.getElementById("header");
content = document.getElementById("content");
mainHolder = document.getElementById("mainHolder");
expandCollapseBtn = header.getElementsByTagName('img')[0];
heightValue = mainHolder.offsetHeight;
header.addEventListener('click', handleClick, false);
mainHolder.addEventListener('webkitTransitionEnd',transitionEndHandler,false);
function handleClick() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
mainHolder.style.height = "26px";
content.style.display = "none";
}
else
{
mainHolder.style.height = heightValue + "px";
}
}
function transitionEndHandler() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
expandCollapseBtn.src = "expand1.png";
}
else{
expandCollapseBtn.src = "collapse1.png";
content.style.display = "block";
}
}
This is fine if the content is static, but I'm trying to populate my div dynamically like so.
This is called from an iphone application and populates the div with a string.
var method;
function myFunc(str)
{
method = str;
alert(method);
document.getElementById('method').innerHTML = method;
}
I store the string globally in the variable method. The problem I am having is now when I try expand the div I have just collapsed there is nothing there. Is there some way that I could use the information stored in var to repopulate the div before expanding it again? I've tried inserting it like I do in the function but it doesn't work.
Does anyone have any ideas?
to replicate:
Here is the jsfiddle. jsfiddle.net/6a9B3 If you type in text between
here it will work fine. I'm not sure
how I can call myfunc with a string only once in this jsfiddle, but if
you can work out how to do that you will see it loads ok the first
time, but when you collapse the section and attempt to re open it, it
wont work.
If the only way to fix this is using jquery I dont mind going down that route.
is it working in other browsers?
can you jsfiddle.net for present functionality because it is hard to understand context of problem in such code-shoot...
there are tonns of suggestions :) but I have strong feeling that
document.getElementById('method')
returns wrong element or this element not placed inside mainHolder
update: after review sample in jsfiddle
feeling about wrong element was correct :) change 'method' to 'info'
document.getElementById('method') -> document.getElementById('info')
I think you want to use document.getElementById('content') instead of document.getElementById('method') in myFunc.
I really see nothing wrong with this code. However, a guess you could explore is altering the line
content.style.display = "none";
It might be the case that whatever is displaying your html ( a webview or the browser itself) might be wiping the content of the elemtns, as the display is set to none

Toggle div by triggering and image click mechanism

I am currently working with the toggle div function. I am using images to be the triggering point for toggling. For example when a div is close an image with a "plus" signs appears to indicate the user to expand and vice versa for compressing the div. The only issue is that I am using two sets of images for expanding and compressing divs but I can only get a set to work but not both. The is example I have doesn't work well in jsfiddle but if you like to look at it there here is the link: http://jsfiddle.net/sQnd9/4/
Here is my example:
<script type="text/javascript">
function toggle1(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="images/Plus_Circle.png"/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="images/Minus_Circle.png"/>';
}
}
</script>
<script type="text/javascript">
function toggle2(showHideDiv2, switchImgTag2) {
var ele = document.getElementById(showHideDiv2);
var imageEle = document.getElementById(switchImgTag2);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src=images/arrow_open.png/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src=images/arrow_close.png/>';
}
}
</script>
<div><a id="imageDivLink" href="javascript:toggle1('contentDivImg', 'imageDivLink');"><img src="images/Plus_Circle.png";/></a>Example</div>
<br />
<div id="contentDivImg" style="display:none;">
Example1-Content
</div>
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
<br />
<div id="contentDivImg2" style="display:none;">
Example2-Content
</div>
The problem isn't your code (other than the mistakes that #appclay pointed out). The problem is jsfiddle. Just look at the source code it produces. When you put anything in the "javascript" section it's puts it in it's own namespace, preventing access to those function names outside of that block (so your call to toggle1 for example was throwing an undefined function error).
You can see this in action by defining these functions directly as window. properties. Then your code works as expected. See http://jsfiddle.net/sQnd9/7/
In your own code, you presumably would not encapsulate these function names into their own scope, and it would work as expected (but note again that you should make the changes #appclay pointed out).
Also, you probably shouldn't be doing it this way anyway. You should attach the event handlers in the javascript block.
You're missing the quotes on the img src attribute in the second one
You're also referencing the first function in both examples, so the second function never gets called... Try changing:
<div><a id="imageDivLink2" href="javascript:toggle1('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
to
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/arrow_open.png" /></a>Example2</div>
Also, I don't know why you have semicolons in your img tags, they shouldn't be there.

Categories