How do you make a picture appear onClick using javascript - javascript

here is the html
<div id="first_caption">
<p style="float: left; clear: left">
<a id="light_on" href="#" onclick="myClick()">
<img id="light_img" src="http://www.ottawaskeptics.org/images/stories/lightbulb.jpg" height="50" width="50">
</a>
How can you stay healthy and do more of the things you love? Click the light bulb to find out how.
</p><br><br><br>
</div>
<div id="heading1">
</div>
here is the javaScript
<script>
function myClick(){
text = "<b><i><br><br>You can save a ton of money by drinking tap or filtered water, instead of wasting hundreds of dollars on bottled water. Did you know the average person spends $100+ per person every year! The good thing is its not your fault; many people are inticed by clever advertising, and thinking it has neutrisional values that other water does not contain. The truth is Big companies like Nestle and Coca'cola are simply profiting off making you think youre making a healthy choice. Bottled water is only tested once a weak for contamination and germs, and is no better than your average tap water. Honestly, if you really wanted to make a healthier decision try filtered water. You could argue that you still have a water bill dont you? well, according to STATISTIC BRAIN,'the total cost of a monthly water bill if tap cost as much as the cheapest watter bottle would be $9000!' </i></b>";
document.getElementById('heading1').innerHTML = document.getElementById('heading1').innerHTML + text;
document.getElementById("heading1").style.textAlign="left";
document.getElementById("heading1").style.marginLeft="20px";
}
</script>
Basically after i click the light bulb some text appears below the picture. I would like to know using the same method how can i make a picture appear instead.

Change the "text" content, and do not append it, just overwrite:
<script>
function myClick(){
text = "<img src='http://www.online-image-editor.com/styles/2013/images/example_image.png'";
document.getElementById('heading1').innerHTML = text;
}
</script>

You can create an img element in the html with style="display: none;" and then get this element and set the new style with display: block; inside myClick() function

You could add the image to your HTML code and set display property to none and then change it with javascript.
HTML
<div id="first_caption">
<p style="float: left; clear: left">
<a id="light_on" href="#" onclick="myClick()">
<img id="light_img" src="http://www.ottawaskeptics.org/images/stories/lightbulb.jpg" height="50" width="50" />
</a>
How can you stay healthy and do more of the things you love? Click the light bulb to find out how.
</p><br><br><br>
</div>
<div id="heading1">
<img id="myNewImage" src="" /> <!-- your new image -->
</div>
CSS
#myNewImage { display:none; }
Javascript
function myClick() {
document.getElementById("myNewImage").style.display = "block";
}

Related

How can I make a "read-more" button for mutiple text elements?

I have multiple images on my website with some text about each image.
<div>
<h2>I still get butterflies</h2>
<p>
A virtuoso display of personality. A sophisticated layered piece that depicts dynamism and vibrancy while also betraying the turmoil and tranquility of humanity. The artist’s ode to the enduring Metamorphosis of an individual and so
much more.
<span id="text">
<br />
The artist’s personality is on full display. A breathtakingly beautiful piece; full of energy, light, sorrow, and pain. The artist’s vision will shake you to the very core. This hauntingly post-modernist piece is an exercise in
raw emotion on canvas; that demands the full attention of the viewer. It is a raw un-tempered glimpse into the fabric of humanity. The vibrancy of colors harmoniously interact with the chaotic themes on display. This artwork
pulls you in, what message you see in it, what themes you feel the artwork depict are entirely up to you. It will touch everyone differently. You and your guest will see a part of you depicted on the painting, a facet of your
life laid bare.
<br />
"I still get butterflies" is a fascinating portrayal of humanity. The dance of colors, the vibrant display of personality and the chaotic themes on display perfectly gel together to depict the elegance and the reality
of existence.
</span>
</p>
<button id="toggle" class="astext">Read More</button>
</div>
<div>
<h2>To levitate</h2>
<p>
"To levitate" is a thoughtful, emotional piece that transcends the fabric of reality. This piece appeals directly to the senses, beneath the incessant and formidable dance of colors is a rapturous delight. Ecstasy, so
profound, so pure that it borders on angelic transformation.
<span id="text">
<br />
"To levitate" is at its heart a deeply disquieting and disturbing display of strange nature that is at once entirely realistic and yet almost supernatural. It conveys a message of self-realization and self-acceptance:
to break free from the chaos of life. The artist portrays a dazzling song that is beautifully pure. "To levitate" is a majestic creation of colors. It betrays the indefinable aroma of the artist&apos;s sincerity to
their vision and intercourse with reality. The message of the piece transcends reality, borders on the supernatural, yet within that artistic expression is perhaps the most human message of all.
<br />
"To levitate" is a deeply feverish piece. At first glance the piece conveys a sense of chaos; it blends the supernatural with reality, but beneath all that chaos lies the harmony of colors, the artist&apos;s intention,
and a beautifully sublime message.
</span>
</p>
<button id="toggle" class="astext">Read More</button>
</div>
<div>
<p>January 14<sup>th</sup>, 2021</p>
<img data-src="./images/portfolio/5524E4534A898F56064C481CD305C703.webp" class="lazyload" alt="my image" />
</div>
The access text is hidden with css #text {display: none;}
Alongside with the HTML & CSS goes JS/jquery code to show the rest on the buttonclick
$(document).ready(function() {
$("#toggle").click(function() {
var elem = $("#toggle").text();
if (elem == "Read More") {
//Stuff to do when btn is in the read more state
$("#toggle").text("Read Less");
$("#text").slideDown();
} else {
//Stuff to do when btn is in the read less state
$("#toggle").text("Read More");
$("#text").slideUp();
}
});
});
Is there a way to show the text according to what button was clicked, without having a seperate script for each?
First of all, use classes instead of IDs in this case. Having multiple elements with the same ID is a big no-no. Then, make the use of jQuery's $(this), along with the sibling and children selectors, to get what you want. $(this) selects only the element you just clicked, and siblings/children will only target the text elements that are directly related to that button within the same div. This Codepen has a live demo.
HTML:
<div>
<h2>I still get butterflies</h2>
<p>
A virtuoso display of personality. A sophisticated layered piece that depicts dynamism and vibrancy while also betraying the turmoil and tranquility of humanity. The artist’s ode to the enduring Metamorphosis of an individual and so
much more.
<span class="text">
<br />
The artist’s personality is on full display. A breathtakingly beautiful piece; full of energy, light, sorrow, and pain. The artist’s vision will shake you to the very core. This hauntingly post-modernist piece is an exercise in
raw emotion on canvas; that demands the full attention of the viewer. It is a raw un-tempered glimpse into the fabric of humanity. The vibrancy of colors harmoniously interact with the chaotic themes on display. This artwork
pulls you in, what message you see in it, what themes you feel the artwork depict are entirely up to you. It will touch everyone differently. You and your guest will see a part of you depicted on the painting, a facet of your
life laid bare.
<br />
"I still get butterflies" is a fascinating portrayal of humanity. The dance of colors, the vibrant display of personality and the chaotic themes on display perfectly gel together to depict the elegance and the reality
of existence.
</span>
</p>
<button class="toggle astext">Read More</button>
</div>
<div>
<h2>To levitate</h2>
<p>
"To levitate" is a thoughtful, emotional piece that transcends the fabric of reality. This piece appeals directly to the senses, beneath the incessant and formidable dance of colors is a rapturous delight. Ecstasy, so
profound, so pure that it borders on angelic transformation.
<span class="text">
<br />
"To levitate" is at its heart a deeply disquieting and disturbing display of strange nature that is at once entirely realistic and yet almost supernatural. It conveys a message of self-realization and self-acceptance:
to break free from the chaos of life. The artist portrays a dazzling song that is beautifully pure. "To levitate" is a majestic creation of colors. It betrays the indefinable aroma of the artist&apos;s sincerity to
their vision and intercourse with reality. The message of the piece transcends reality, borders on the supernatural, yet within that artistic expression is perhaps the most human message of all.
<br />
"To levitate" is a deeply feverish piece. At first glance the piece conveys a sense of chaos; it blends the supernatural with reality, but beneath all that chaos lies the harmony of colors, the artist&apos;s intention,
and a beautifully sublime message.
</span>
</p>
<button class="toggle astext">Read More</button>
</div>
<div>
<p>January 14<sup>th</sup>, 2021</p>
<img data-src="./images/portfolio/5524E4534A898F56064C481CD305C703.webp" class="lazyload" alt="my image" />
</div>
JS:
$(document).ready(function() {
$(".toggle").click(function() {
var elem = $(this).text();
if (elem == "Read More") {
//Stuff to do when btn is in the read more state
$(this).text("Read Less");
$(this).siblings().children('.text').slideDown();
} else {
//Stuff to do when btn is in the read less state
$(this).text("Read More");
$(this).siblings().children('.text').slideUp();
}
});
});
It looks like you are using jQuery already. You might want to consider using the toggle() function, which is just for this purpose:
https://www.w3schools.com/jquery/eff_toggle.asp
$("#toggle").click(function(){
$("#text").toggle();
});

jQuery - Want to restrict a function to only elements within one div using

Bascially, I have this:
<div class="articlecontainer">
<div class="image"><img src="some_image.jpg"></div> <!----image is floated left--->
<div class="content">
<p>
Some text about the image.
Some text about the image.
Some text about the image.
</p>
<span class="morelink">Link to Read More</span>
<div class="more">
<p>
More text about the image.
More text about the image.
More text about the image.
</p>
</div> <!--- close more --->
</div> <!--- close content --->
</div> <!--- close articlecontainer --->
I want my function to run ONLY on <div class="image"> within the same <div class="articlecontainer"> div as the link in <span class="morelink">.
Is this possible? How can I do it?
I know I could do this by giving everything an ID and repeating the function for each article using the different IDs, but that doesn't seem efficient to me.
Here is what I am doing currently:
Widths are defined. The only thing I am changing is height.
I have an image next to a block of text. This block of text is inside a div with the .content class. Those divs start at one height (dependent on the amount of text in it), but the height can increase if a "read more" link is clicked.
The images have the .image class, and initial height of that class is dictated by the height of the content div. When "Read More" link is clicked, the "more" div is shown, and the image is displayed at 100% height.
I want to use classes because I have multiple articles that follow this same pattern and I don't want to have several repeating IDs that do the same thing.
The problems:
Due to using classes, the height for all images with the .image class is initially set by the first div with the .content class, and when any "read more" link is clicked, all images are expanded.
What I want to do:
I would like to tie the image height, content height, and "read more" link together. I.e., when the "more" link is clicked in Article 1, it only affects Article 1, when the "more" link is clicked in Article 2, it only affects Article 2 and so on.
Is this possible?
Pen of what I'm doing currently:
http://codepen.io/adamcycle/pen/qRRzja
Made few code changes in your javascript. Is it what you want?
var more1height = $("#more1").height();
var more2height = $("#more2").height()
$("#more1, #more2").hide();
var imgHeight = $(".pic").height();
var contHeight = $(".content").height();
$(".image").height(contHeight);
$("#more1link").click(function() {
var image = $('#more1').parent('.content').siblings('.image');
if ($('#more1').is(":visible")) {
$("#more1").hide(200);
image.height(contHeight);
} else {
$("#more1").slideDown(200);
image.height(contHeight+more1height);
}
});
$("#more2link").click(function() {
var image = $('#more2').parent('.content').siblings('.image');
if ($('#more2').is(":visible")) {
$("#more2").hide(200);
image.height(contHeight);
} else {
$("#more2").slideDown(200);
image.height(contHeight+more2height);
}
});
.articlecontainer {
margin-bottom: 15px;
overflow: auto;
}
.content {
width: auto;
padding: 0 15px;
overflow: hidden;
line-height: 1.6;
margin-top: -20px;
}
.content h3 {
margin-top: -6px;
font-weight: 400;
}
.image {
float: left;
width: 450px;
overflow: hidden;
display: block;
border: 2px solid #f5f5f5;
}
.pic {
width: 100%;
}
.morelink {
color: gray;
cursor: pointer;
}
.more {
display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="articlecontainer">
<h2>Cat 1</h2>
<div class="image"><img src="http://i.imgur.com/znXfFyn.jpg" class="pic" alt="cat" /> </div>
<div class="content">
<p>Cat not kitten around flop over drink water out of the faucet and chase ball of string. Sleep on dog bed, force dog to sleep on floor. Cats secretly make all the worlds muffins meowing non stop for food. Shove bum in owner's face like camera lens fall over dead (not really but gets sypathy) for instantly break out into full speed gallop across the house for no reason russian blue wake up human for food at 4am wake up human for food at 4am but jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed.</p>
<p><span class="morelink" id="more1link"><em>Read More</em></span>
<div class="more" id="more1">
<p>Have my breakfast spaghetti yarn unwrap toilet paper yet bleghbleghvomit my furball really tie the room together but cough furball or lick yarn hanging out of own butt, love to play with owner's hair tie lick butt and make a weird face. Have secret plans mrow and lay on arms while you're using the keyboard or stare at the wall, play with food and get confused by dust has closed eyes but still sees you run in circles, yet knock dish off table head butt cant eat out of my own dish. </p>
</div><!--- end more --->
</div><!--- end content --->
</div><!--- end articlecontainer --->
<div class="articlecontainer">
<h2>Cat 2</h2>
<div class="image"><img src="http://i.imgur.com/ocquBvl.jpg" class="pic" alt="cat" /> </div>
<div class="content">
<p>Cat not kitten around flop over drink water out of the faucet and chase ball of string. Sleep on dog bed, force dog to sleep on floor. Cats secretly make all the worlds muffins meowing non stop for food.</p>
<p><span class="morelink" id="more2link"><em>Read More</em></span>
<div class="more" id="more2">
<p>Have my breakfast spaghetti yarn unwrap toilet paper yet bleghbleghvomit my furball really tie the room together but cough furball or lick yarn hanging out of own butt, love to play with owner's hair tie lick butt and make a weird face. Have secret plans mrow and lay on arms while you're using the keyboard or stare at the wall, play with food and get confused by dust has closed eyes but still sees you run in circles, yet knock dish off table head butt cant eat out of my own dish. </p>
</div><!--- end more --->
</div><!--- end content --->
</div><!--- end articlecontainer --->

jQuery fade out fade in replaces text while jumping instead of overlaying

The below code is running on the following web page. If you click any of the three buttons on the left under the rotating banner you will see the behaviour I talk about. The text next to the buttons is meant to fade out and fade in a new section. But the new section fades in before the first is gone and jumps back up.
I thought as I was using a callback function for the fade in that this would not occur. Can anyone advise as to what I should be doing?
http://www.tacticalsalestraining.co.uk/
<span style="float:left;">
<a target="_blank" href="http://www.tacticalsalestraining.co.uk/sales-training-courses-listing" class="textbutton" data-conn="text1">
<img src="/images/OpenOver.png" alt="Open Courses" width="300" height="47">
</a><br />
<a target="_blank" href="http://www.tacticalsalestraining.co.uk/sales-training-courses-listing" class="textbutton" data-conn="text2">
<img src="/images/InHouseOver.png" alt="In House Training" width="300" height="47">
</a><br />
<a href="http://tacticalsalestraining.com/seminars/seminars_full.html" class="textbutton" data-conn="text3">
<img src="/images/FreetoAttendOver.png" alt="Free to Attend" width="300" height="47">
</a>
</span>
<span style="width:610px;height:200px;float:right; background-color:#bcbcbc;font-size:15px;line-height:15px;">
<div class="texts" id="text"><h1>UK's Fastest Growing Sales Training Company</h1>
Tactical Sales Training, providers of measurably effective sales courses for all industries. We offer training that's interactive, effective and straight out of our own playbook.<br />
We practice what we teach; the courses are filled with exactly what we do back in the office when prospecting for new clients or looking to close deals.
</div>
<span class="texts" id="text1" style="display:none;"><h2>Action Based Open Sales Courses, Nationwide</h2>
Trouble getting new business? Difficulty closing that deal? How's your qualification going? These are questions that can define the difference between a good or great sales person. We've helped 100s of businesses exponentially increase their sales with our open courses, what can we do for you?
</span>
<span class="texts" id="text2" style="display:none;"><h2>For the More Tricky Sales Processes</h2>
Getting to the root of the problem or finding the perfect solution can be a call for our bespoke option. Many national and international companies have opted for this because they wanted us to look deep into their sales processes.<br /><br />
They also wanted the perfect solution with instantly actionable solutions that prove the effectiveness with measurable results. We've provided just that, every single time we go out on a bespoke mission.
</span>
<span class="texts" id="text3" style="display:none;">Content Text</span>
</span>
<script>
$(".textbutton").click(function(){
var link = $(this).attr("data-conn");
$(".texts").fadeOut(1000, function() {
$("#"+link).fadeIn(1000);
});
return false;
});
</script>
One problem with your script is that you apply fadeOut on all items with texts class & try to fadeIn one of them back. The better approach would be to keep track of the current selected text, say by adding another class selected.
Here is the modified script you could work on. One of the items with texts class has to have the selected class all the time.
$(".textbutton").click(function(){
var link = $(this).attr("data-conn");
$(".texts.selected").removeClass("selected").fadeOut(1000, function() {
$("#"+link).addClass("selected").fadeIn(1000);
});
return false;
});
$(".texts:first()").addClass("selected");

How to split some html content by "page breaker"?

I use ckeditor in my website, which supports "page breaker". The sample content contains page breakers like:
<h1>
Little Red Riding Hood</h1>
<p>
"<b>Little Red Riding Hood</b>" is a famous fairy tale about a young girl's encounter with a wolf. The story has been changed considerably in its history and subject to numerous modern adaptations and readings.</p>
<div style="page-break-after: always;">
<span style="display: none;"> </span></div>
<p>
The version most widely known today is based on the Brothers Grimm variant. It is about a girl called Little Red Riding Hood, after the red hooded cape or cloak she wears. The girl walks through the woods to deliver food to her sick grandmother.</p>
This special div is page breaker:
<div style="page-break-after: always;">
<span style="display: none;"> </span></div>
I want to use javascript to split the content into multi pages by the page breaker, to tell the user how many pages the content will be, and can let user preview each page.
But how to check and split it? Is there a pure javascript or "Extjs" based solution?
You can use the String.prototype.split(); function for this: container.innerHTML.split('<div style="page-break-after: always;">');, assuming the container for your HTML code to be container.
You can use Regular Expressions for this:
var regexp = /<div\s+style=('")page-break-after:\s*always;?.*?$1[^>]*>.*?<\/div>/gm;
Which will find all the breaker DIVs for you. You can then split the string using that.
Use regex:
content.split(/<div style="page-break-after: always;">[\s\S]*?<\/div>/)
Is there a better way for [\s\S] part? I think it's a little strange.
HTML:
<form name="myform">
<input type="checkbox" name="mybox" onClick="breakeveryheader()">
</form>
JavaScript:
function breakeveryheader(){
var thestyle=(document.forms.myform.mybox.checked)? "always" : "auto"
for (i=0; i<document.getElementsByTagName("H2").length; i++)
document.getElementsByTagName("H2")[i].style.pageBreakBefore=thestyle
}

How come the hyperlink doesn't work on part of my div?

http://geodit.com:8000/
If you try to click between "Spear St. Oakland" and the description, you'll notice that the anchor takes you nowhere. That's because there's a padding between them.
How do I get the hyperlink to work when the user clicks between the text?
Try putting the padding on the a element(s), instead of the div elements.
Your code is unnecessarily complex. For example you don't need to wrap everything (such as each link) in a DIV (or the other way round). Just style the link directly, possibly setting it's display style to block so that it behaves like a div.
If you merge both links into one then your problem will go away and you wouldn't need to "fake" the links with cursor: pointer.
Here an example how simple your HTML could be:
<div class="awallpost grid_doc_holder sub" data-image="http://s3.amazonaws.com/fabletest/7cgeq8hkdt">
<a href="/d/1339" class="trans_caption ">
See the sun whispering the light of our days from last summer...
</a>
<div class="trans_caption_over">
<img src="/media/img/brightmix/star.png"> Great Find!
<a href="/d/1339" class="extras">
<em><img src="/media/img/brightmix/placedot2_white.png" align="texttop" width="12" height="auto"> Spear St. Oakland, 94107</em>
<span>Hey it's weekend! Whohoooo :O) Made a few new photos on my favorite heathland just outside the city, the sunset ...</span>
</a>
</div>
<div class="title_text_only">
See the sun whispering the light of our days from last summer...
</div>
<div class="desc_text_only">
Hey it's weekend! Whohoooo :O) Made a few new photos on my favorite heathland just outside the city, the sunset was so gorgeous and soft just perfect for my &amp;quot;cream ...
</div>
</div>
You do not have a link between the text. You have TWO links.
What is confusing is the
.grid_doc_holder {
cursor: pointer;
text-align: center;
}
which shows the hand when you are not over the links too
You could consider making the outer container clickable
I believe you want to just put your div(or Divs) within an A tag, that will make it all clickable.

Categories