Replace image in another div with text upon mouse over elsewhere - javascript

I have tried around a dozen different ways to do this, I'm only going to post my most recent attempts though.
Basically I am trying to have it so that when a user hovers the mouse over an image on the page, another image in a separate div gets replaced with text.
I have the JS variables for the text elements to replace as well as the original image being replaced to put it back.
My most recent attempts were:
function replaceMainPage(x) {
$('#logozone').empty();
$('#logozone').append(x);
}
function hoverCircles(y) {
$(this).hover(replaceMainPage(y), replaceMainPage(mainLogo));
}
I don't really understand the "this" feature of JS, but have also tried that function as:
function hoverCircles(y) {
$('#logozone').hover(replaceMainPage(y), replaceMainPage(mainLogo));
}
From here I have tried calling the function is my main JS file like so:
$("#cir1").hover(replaceMainPage(logoReplacements.cakes), replaceMainPage(mainLogo));
As well as tried doing it in html on the img element itself with a onmouseover. Nothing has worked yet.
Am also open to non-JS ways of handling this, but I looked for those as well and couldn't find anything.

This will help you, here is a jsFiddle:
var oldContent = '';
$('.hoverMe').hover(function() {
oldContent = $('.toReplace').html();
$('.toReplace').html('xxxxxxxx');
}, function() {
$('.toReplace').html(oldContent);
});
HTML
<div class="hoverMe">
HOVER ME
</div>
<div class="toReplace">
<img src="//cdn2.hubspot.net/hub/360031/hubfs/feature_practicetest.jpg?t=1470774914678&width=365">
</div>
I've created a global variable called oldContent. When hover on the .hoverMe div, store the old content of that div, change the content of div, and when you move your mouse out, put back the old content.
UPDATE
Based on OP comment, I create another jsFiddle where you can set any text on the .hoverMe
If there are longer texts, or kind of texts what can not be stored in the data attribute, then add data-id="1" to n, and retreive the text through ajax based on the id.

HTML
<div id="firstImgDiv">
<div class="text"></div>
<img src="a.png" onmouseenter="replaceImg('secondImgDiv', 'new Text')">
</div>
<div id="secondImgDiv">
<div class="text"></div>
<img src="b.png" onmouseenter="replaceImg('firstImgDiv', 'new Text')">
</div>
JS
function replaceImg(id, text){
// show all images again
$('img').show();
// clear all text
$('.text').html('');
// hide target img
$('#'+id+' > img').hide();
// set target text
$('#'+id+' > .text').html(text);
}

Related

How to link two html pages

So i'm working on a chat application and i want to add smileys. So i used two html pages. the first one contain the text area when we wright the messages and an iframe that references the second html page.
<div class="col-12">
<textarea class="col-12 row-12 var_MessageInput" id="textmsg" placeholder="Write a reply..."></textarea>
</div>
in the second html page i have smiley images
<img src="../../../images/sad_smile.gif" onclick="insertSmiley('sad');"/>
<img src="../../../images/angel_smile.gif" onclick="insertSmiley('angel');"/>
<img src="../../../images/happy_smile.gif" onclick="insetSmiley('happy');" />
So i want that when i click at a smiley image that a text got inserted in my text area so i used the following script
function insertSmiley(smiley) {
var currentText = document.getElementById("textmsg");
var smileyWithPadding = " " + smiley + " ";
currentText.value += smileyWithPadding;
currentText.focus();
}
But it doens't work :( i thought the problem might be in document.getElementById since it's another html page but i have no idea how to solve it.
Thanks a lot
Have you included the <script src="Scripts_Chatapp/emoticone.js"></script> in iframe too? If yes, remove the script reference from iFrame.
Move the script reference <script src="Scripts_Chatapp/emoticone.js"></script> at top of page with other script tags.
Change the onclick="insertSmiley('sad');" TO onclick="parent.insertSmiley('sad');".
This will call the parent function and make changes on that page, since element exists on parent.
You have one typo in onclick="insetSmiley('happy');" it should be onclick="insertSmiley('happy');". I checked it and it works for me.
In your JS code, use:
window.location = "second_HTML_Page.html" ;
The problem is that when the function is triggered within the iFrame, the scopes become complicated.
A solution would be to make the function global by defining it at the window level. And then when the function is to be triggered inside the iFrame, it can call the function of the iFrame's parent (the main window).
Example Fiddle: http://jsfiddle.net/e37rrtb1/2/

Image hide and show not working

I am using this jquery.smoothZoom.min.js to zoom and pan image.I have successfully applied that to my project for single image,now i want to add (<,>.i.e. corousal) ,so that I can use it for multiple images.When I add the corresponding part in my custom.js it does not work properly.
I will attach two screen sorts which will clear the picture
This is the first case
and after clicking the right corousal button
I can see only the background but not the required image . I can not understand what i am missing ,
This the html part i have been using
<div class="image-display" id="displayplan4" style="width:70%;height:120%; left:39%;top:10%;position:absolute;display:none;">
<img src="images/amenities.jpg" style="width:150%;height:130%; left:-60%;top:-20%;position:absolute;overflow:auto; z-index:1;">
<div style="width:150%;height:130%; left:-60%;top:-20%;position:absolute;background:rgba(255,255,255,0.7);z-index:2;">
</div>
<img class="planzoom" src="gallery/Residential/ongoing/Almog/Plan/almog1.jpg" id = "almogplan0" style="width:100%;height:100%; right:3%;top:50%;position:absolute;z-index:3;">
<!--button for forward and backward movement-->
</div>
and
<div id = "almogplandivII">
<img class="planzoom" src="gallery/Residential/ongoing/Almog/Plan/almog2.jpg" id= "almogplan1" style="width:100%;height:100%; right:3%;top:50%;position:absolute;z-index:3;display:none;">
</div>
and the corresponding js part to show and hide image on mouse click upon the image.
var almog_plan_div=0;
//Function for image forward with forward button
$("#almogforward").click(function ()
{
if(almog_plan_div<1)
{
$("#almogplan"+almog_plan_div).hide();
almog_plan_div++;
$("#almogplan"+almog_plan_div).show();
}
else
{
$("#almogplan"+almog_plan_div).hide();
almog_plan_div=0;
$("#almogplan"+almog_plan_div).show();
}
});
//Function for image backward with backward button
$("#almogback").click(function ()
{
if(almog_plan_div>0)
{
$("#almogplan"+almog_plan_div).hide();
almog_plan_div--;
$("#almogplan"+almog_plan_div).show();
}
else
{
$("#almogplan"+almog_plan_div).hide();
almog_plan_div=1;
$("#almogplan"+almog_plan_div).show();
}
});
I have tried like adding display:none style properties but it does not help my cause,
any help on this ?
Remove inline styling display: none from the img tag and then when u initialize your page, then hide that image using hide() function.
Inline-styling might be overriding this
Thanks to both of your answers ,both of u may not be exactly correct but definitely helped me getting me my solution.
The trick i was missing:
I) have used two different divs ,but i have not positioned the second one, (I noticed only that when I tried the whole thing in a new web page with only 2 images in it ,they were not positioned properly )my requirement needs the divs to be hidden ,i had to hide them.
2) The other thing i had to remove was the position:absolute thing from individual image elements.
Once rectified its cool now.

Using Javascript to show/hide elements depending on content in div

I am relatively inexperienced with JavaScript, and I'm working on a project that's turned into a real trial by fire for me, but hopefully this is a question that has a stupidly straightforward answer.
I'm trying to write a script that will show/hide different links on a page by changing the display style of different links.
I want to use a div element and have different links available if the user drags different images into the div. The links are in clickable pictures.
Example-
I want this linked element 'link' to be displayed only if "First_Image.png" has been dragged and dropped into div2:
<a id='link' href='link.html' style='display: none;'><IMG src="../Image.png"></a>
My div id is "div2", and it starts out empty as such:
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
Images on the page are set up as:
<IMG src="First_Image.png" id="First_Image" draggable="true"
ondragstart="drag(event)">
There are several such droppable images on the page. My attempt at this script is:
<script>
if (document.getElementById("div2").getElementsByTagName('img') == "First_Image")
document.getElementById('link').style.display = 'block';
return (false);
</script>
I'm not sure if my problem is that I'm not getting the information I think I am from the image in the div, or if my simple if statement isn't doing what I think it's doing. :/
If you're trying to get the values from the attributes (as the src is an attribute). You can try out Element.getAttribute.
https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
document.getElementById("div2").getElementsByTagName("img").getAttribute("src");
Step by step would be:
var id = document.getElementById("div2");
var elem = id.getElementsByTagName("img");
var atr = elem.getAttribute("src");
/* for comparing */
if(atr == "First_Image.png") {
return false;
}
This will produce this: First_Image.png. And also, write this:
return false; /* not (false) */
I think the error is in your comparison
if (document.getElementById("div2").getElementsByTagName('img').src.indexOf("First_Image") > -1)

(jQuery) Find and Replace specific text

I've got the following HTML code, which essentially pertains to a post where I announce something in just a few lines, end it with "[...]", and add a "Read more" link-button at the bottom. When this button is clicked, additional content that's hidden will fadeIn as the button disappears, leaving visible the introductory text and the one that was hidden -- simple enough. Now, I've already written the code for this, but the complication comes when I try to also remove that "[...]" (from the post where the click button happened) that I included in the sneak peek. Here's the HTML:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span id="revealer" class="button">Read more</span>
</div>
Classes "entry" and "button" belong to my CSS file, while "slide-content" belongs to my .js file to control the fadeIn effect. The ID "revealer" also belongs to the .js file for the same purpose. This HTML is wrapped in a div tag with a class of "box". This is the format that each post follows, exactly the same format with the same HTML elements -- every time an announcement needs to be made, it's just a matter of putting the content between the paragraph tags and publish. Here is where my problem comes in, since I can't find a way to remove the "[...]" only in the post where the button has been clicked. I tried doing the following but it resulted in the deletion of all "[...]" throughout multiple posts:
$('.entry p').each(function() {
var textReplace = $(this).text();
$(this).text(textReplace.replace('[...]', ''));
});
Summary:
I need to remove the "[...]" text only from the post where the user has clicked on (the "Read more" button). The idea is to have this removed while at the same time the hidden content fades in.
I've been able to accomplish the above but for all instances of "[...]". I need to sophisticate my selection by modifying my jQuery code or the HTML.
Option 3 is to get rid of this "[...]", but I would like to leave it there to let the user know she has more content to read, and I would like to have that "Read more" button in all posts for consistency.
~Thanks in advance!
First, you mention you have multiple of these. In that case, this:
<span id="revealer" class="button">Read more</span>
will not work. id attribute has to be unique per document, i.e. you can have at most one element with the specific id value.
If you make your HTML (for each of the blocks) like this:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span class="revealer button">Read more</span>
</div>
and your JS like this:
function replace(fromp) {
var textReplace = fromp.text();
fromp.text(textReplace.replace('[...]', ''));
}
$('.revealer').click(function() {
var fromp = $(this).siblings().eq(0);
replace(fromp);
});
it will work properly. Working example:
http://jsfiddle.net/G4t7Q/
Hope this helps.
When you run your page initialization script, you could use jquery to select all of the posts and all of the remove buttons and link them up via their click event. I've created a JSFiddle example, but here's the jist of it:
var removers = $(".remover")
var posts = $(".post")
for (var i = 0; i < removers.length; i++) {
$(removers[i]).click( { post: posts[i] },
function(event) {
var textReplace = $(event.data.post).text()
$(event.data.post).text(textReplace.replace('[...]', ''))
}
)
}​
This is a simplified example; it assumes the posts and buttons are sorted in the markup.

How can accomplish a dual div swap on rollover?

I am looking for advice on a way to accomplish this. Given the following:
[Div A (contains an image)]
[Div B (contains a horizontal list of 8 or so text links)]
[Div C (contains text)]
Upon rolling over any link in Div B, how can I have Div A and Div C swap their respective contents out to something different that corresponds to the content of that link?
For example, if one were to rollover a Div B link called "Dogs", then upon that rollover, Div A would replace its contents and display an image of a dog and Div C would replace its contents and display text about dogs.
After rolling over that link, the new Div A and Div C contents will remain in place until a new link is rolled over.
I hope this makes sense. Does anyone have advice on the best way to accomplish this?
Assuming the href points to one resource that contains the content for both, but you can't just inject the entire output of the link into one element, something like this could work:
$('#divB a').mouseover(function() {
//get images from link, inject into divA
$('#divA').html('<strong>Loading...</strong>')
.load($(this).attr('href') + ' img');
//get divs from link, inject into divC
$('#divC').html('<strong>Loading...</strong>')
.load($(this).attr('href') + ' div');
});
Hmm... this should be pretty simple with jQuery (compared to some of the other answers here):
If you're unfamiliar with jQuery, the $() is a shortcut for calling jQuery(), and using
$(document).ready(function() {
// put all your jQuery goodness in here.
});
is a way to make sure jQuery fires at the right time. Read more about that here.
So first, add a class (ie .dogs) to each <a> element in your #divB list. Next, give each of the corresponding images the same class, and contain each of your text blocks in #divC in divs with the same class as well. The HTML would look something like this:
<div id="divA">
<img src="dogs.jpg" class="dogs" />
<img src="flowers.jpg" class="flowers" />
<img src="cars.jpg" class="cars" />
</div>
<div id="divB">
<ul>
<li>Dogs</li>
<li>Flowers</li>
<li>Cars</li>
</ul
</div>
<div id="divC">
<div class="dogs"><p>Text about dogs.</p></div>
<div class="flowers"><p>Text about flowers.</p></div>
<div class="cars"><p>Text about cars.</p></div>
</div>
Then use the following jQuery, putting this up in the <head> section of your HTML doc:
$(document).ready(function() {
$('a.dogs').hover(function() {
$('#divA img').hide("fast");
$('#divA img.dogs').show("fast");
$('#divC div').hide("fast");
$('div.dogs').show("fast");
});
});
We say when the document is ready, when you hover over the <a> element with the .dogs class, perform a function. That function will hide all of the images in #divA and immediately show the image with the .dogs class. Then it will hide all of the divs in the #divC and immediately show the div with the .dogs class.
You can do the same thing twice more for .flowers and .cars, or however many you have.
Keep in mind, there are more efficient ways of doing this too, if you're interested in looking deeper into jQuery, but this will be a solid way to get started in helping you understand exactly what jQuery is doing. And it keeps the script OUT of the HTML body, too!
You can change a div's contents with something like this:
<script type="text/javascript">
function over() {
var a = document.getElementById('a');
var c = document.getElementById('c');
a.style.backgroundImage = "url(/path/to/image)";
c.innerHTML = "<b>Dogs rock</b>";
}
</script>
<div id="a"></div>
<div id="b" onmouseover="over();"></div>
<div id="c"></div>
Then all you need to do is add whatever other div's you want and write code to change them appropriately. Set the initial state of A and C using css, or just call the over() function on page load.

Categories

Resources