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

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)

Related

Replace image in another div with text upon mouse over elsewhere

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);
}

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.

javascript-- changing the innerHTML of an image

So I JUST asked a question and I've already hit another roadblock. Thanks so much to the stackoverflow community for helping me out so much recently :)
Every time I see people changing the innerHTML of some tag, they use document.getElementByID(id).innerHTML. My images do NOT have ids, nor do I want to give each and every one of them an id.
Here is my code:
function clickImages()
{
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++)
{
var delegate = function() { hover(this); };
images[i].onmouseover = delegate;
}
}
function hover(img)
{
img.innerHTML = "Text!";
}
The innerHTML doesn't seem like it's working; when I mouse over the image nothing changes.
Thanks in advance! Let me know if I can clarify!
An image is itself a replaced element, so there is no innerHTML to replace.
Based on your comment, if you want to add HTML adjacent to the image, you could do this:
img.insertAdjacentHTML('afterend', 'HTML code');
You could also change 'afterend' to 'beforebegin' if you wanted to add the HTML before the image.
Writing on the image itself would be much more complicated and would require positioning another element above it with a transparent background, or using the image itself as the background of another element, or a variety of other similar techniques.
Element.innerHTML
innerHTML sets or gets the HTML syntax describing the element's
descendants
innerHTML means the HTML that comes between the start and end HTML tags. Images don't have innerHTML
I am not sure what you want to achieve.
If you want to have a text displayed onmouseover, you can use the title attribute to do that.. for example:
<img src="smiley.gif" alt="Smiley face" title="Hello" />
If you are trying to replace the image with text on onmouseover ... then as an example (only to show the possibilities), the following code will hide the image & display a text onmouseover and make the image visible & remove the text onmouseout (although not very satisfactorily IMHO, more work has to be done on the code to improve it)
Please note: There shouldn't be any gap between the image tag and the span for this particular code to work. Also, a negative margin-left added to the span element can make it appear over the location of the image.
<img onmouseover="toText(this)" onmouseout="toImage(this)" src="smiley.gif" alt="Smiley" /><span style="visibility: hidden; margin-left: -30px;">Show Text</span>
function toText(img) {
img.style.visibility = 'hidden';
img.nextSibling.style.visibility = 'visible';
}
function toImage(img) {
img.style.visibility = 'visible';
img.nextSibling.style.visibility = 'hidden';
}
Good luck
:)

Getting HTML content using jQuery on click

I've got a simple application that requires a DIV to be clicked, and in turn it shows another DIV which needs to have its content updated.
There are around 40 items that will need to be clickable and show the correct label for each.
Here is what I need to happen...
User clicks a DIV (drag_me)
Information box DIV is then shown (flavour_box)
the default word 'Ingredients' is swapped out with the content from the "flavour_descrip" div
Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
The data comes from a database, so I'm unable to set individual ID's.
I had a similar issue with draggable's, but that was fixed, and I've tried doign somethign similar to no avail.
Here is the clickable DIV (flavour_descrip is set as hidden in the CSS)
<li class="drag_me">
<div>
<img src="RASPBERRY.png" />
</div>
<div class="choc_label">
Raspberries
</div>
<div class="flavour_descrip">
Our description will appear here for the DB
</div>
</li>
Here is the HTML for the popup box...
<div id="flavour_box">
<p class"flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
Here is the jQuery snippet for the click (i've commented out the code I had started to rejig, but essentially I need to change the draggable.find to something that will work!)
$(".drag_me").click(function () {
//var htmlString = ui.draggable.find('.choc_label').html();
//$('.choc2_flavour').text(htmlString);
// update the description of the item
//var htmlString = ui.draggable.find('.flavour_descrip').html();
//$('.flavour_description').text(htmlString);
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
Any ideas how I can achieve this?
Added extra question
Now I've had my problem resolved, I need to perform one more task.
Inside the div that gets the details passed using "this", I need to be able to pass one more items to a different piece of script.
The DIV 'flavour_add' is clickable and will need to grab the flavour name to use to update some bits on screen and update a URL on the fly.
<div id="flavour_box">
<p class="flavour_name_label">Label</p>
<p class="flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
This is the jQuery I have, but using "this" doesn't seem to work
$(".flavour_add").click(function () {
// hide the ingredient box
$("#flavour_box").toggleClass("hidden");
// show the continue box
$("#added_box").toggleClass("visible");
// get the flavour name
var flavourLabel = $(this).find('.flavour_name_label').text();
// update flavour URL
var _href = $("a.to_step_3").attr("href");
$("a.to_step_3").attr("href", _href + '&flavour=' + flavourLabel);
//$("a.to_step_3").attr("href", _href + '&flavour=TestFromAdd');
// update the mixing bowl list with the ingredient
$('.choc2_flavour').text(flavourLabel);
});
Use $(this) to get the reference to the clicked element:
$(".drag_me").click(function () {
var txt = $(this).find('.choc_label').text();
$("#flavour_box > .flavour_descrip").text(txt);
$("#flavour_box").toggleClass("visible");
});
Besides, there was a "typo" in your html code, replace:
<p class"flavour_description">Ingredients</p>
By:
<p class="flavour_description">Ingredients</p>
You can easily achieve this using jQuery.
$(".drag_me").click(function () {
$('.flavour_description').text($('.flavour_descrip').html());
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
I cannot seem to be able to find the divs for step: 4. Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
I will assume that you mean 'flavour_add' in which case the code should look like this:
$('.flavour_add').text($('.choc_label').html());
Try this:
$(document).ready(function() {
var $flavourBox = $('#flavour_box');
var $flavourDesc = $flavourBox.children('.flavour_description');
var $chocFlavour = $flavourBox.children('.choc_flavour');
$('.drag_me').on('click', function() {
var $this = $(this);
$flavourDesc.html($this.children('.flavour_descrip').html());
$chocFlavour.html($this.children('.choc_label').html());
$flavourBox.addClass('visible'); //toggleClass will remove the class if it is there
});
});
get the text by using "this" (the actual clicked element) and then get the child flavour_descrip div
$(".drag_me").click(function () {
$("#flavour_box").show();
$('.flavour_description').text($(this).find('.flavour_descrip').text());
});
then show the flavour_box div and set the value of the div with the flavour_description class

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