jQuery Mouseover Event is Duplicating - javascript

I'm pretty new to this. I'm trying to trigger a preview of a link via an iFrame, triggered by a hover (mouseover) event.
Here's the JSFiddle of what I have so far: https://jsfiddle.net/80so5jyL/
It works right the first time, but when I hover back and forth on a link more than once, it duplicates the display. How can I ensure that there's only one iFrame popping up every time?
I tried unbinding the mouseover/mouseout events (that commented out line), and it prevents the duplication issue, but also doesn't allow me to display over that same link again, even after I've hovered out, or over a different link (which it still lets me do).
HTML:
<a class="tester" href="http://therainforestsite.com">Link Uno</a>
<a class="tester" href="http://www.example.com">Link Dos</a>
CSS:
.tester { display: block;
margin: 50px;
}`
JS (jQuery):
$("a").mouseover(function() {
var thisURL = $(this).attr('href');
console.log(thisURL);
var theCode = '<style>.preview {display:none;position:absolute;margin-left:0px;z-index:10;border:1px;solid #000;width:100px;height:100px;}</style><iframe class="preview" src="' + thisURL + '"></iframe>';
$(this).append(theCode);
$(this).children(".preview").show();
}).mouseout(function() {
$(this).children(".preview").hide();
//$(this).unbind('mouseover');
return;
});
Any ideas?

Its happening because you are appending it to this everytime and thus it is getting duplicated. Use .html instead and also do not put it inside this i.e. a tag when you use html. Keep it in a separate element, because when you use .html it will replace the contents and a tags text will be gone.
So I would suggest to use below html
Some Link<br/><br/>
Example Link
<p class="bigPreview"></p>
CSS
.bigPreview{
display:none
}
and in JS
$("a").mouseover(function() {
var thisURL = $(this).attr('href');
var theCode = '<style>.preview {display:none;position:absolute;margin-left:0px;z-index:10;border:1px;solid #000;width:100px;height:100px;}</style><iframe class="preview" src="' + thisURL + '"></iframe>';
$('.bigPreview').html(theCode).show(); //put it into .bigPreview and use .show on it
}).mouseout(function() {
$('.bigPreview').html('').hide(); //clear its html and hide it
});

Related

How to load inner html of div from another page?

I'm currently working on a website where the navigation bar links would seamlessly lead to another page with fading transitions without loading.
When the links are clicked, the div#page block, which has the main page content and the footer, would fade out, empty itself, and fade back in with the content of the href of the clicked link. However, my current code, seen below, placing the html of the entire page (including the head contents) on div#page instead of just the inner HTML of div#page.
$("#header .menu a, #header .logo").click(function() {
var href = $(this).attr("href");
var title = $(this).attr("title");
history.pushState(null, title, href);
$("#page").fadeOut("slow", function() {
$("#page").delay(1000).empty();
});
$("#page").load(href + "#page", function() {
$("#page").fadeIn();
});
return false;
});
From the docs
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
So try adding a white-space like so
$("#page").load(href + " #page", function() { //White space before #page
$("#page").fadeIn();
});
PS: I have not tested this code.
Two options:
The recommended way would be to create an API that would return the
inner HTML only.
Parse the response like so (example):
var $dom = $('<div />');
$dom.html(response);
var $content = $dom.find('#id'); // #id is your inner content id
And now you should be able to insert the inner content using $content.html().

How can I hide and element using CSS on initial page load until the Javascript link is clicked

I currently have a webpage that looks like this:
I would like to make it so the "Click to view Gallery of This property" button does not show on the initial load, but does show once the property links are clicked.
Here is an example of my current code:
function changeImage(image, link) {
document.getElementById('imageReplace').src = image;
document.getElementById('linkReplace').href = link;
}
HTML:
TEXT
TEXT
TEXT
<img src="INITALPAGELOADIMAGE" alt="Images" id="imageReplace" class="changeImageClass">
<span style="float: right; padding:2px;"><Button>Click to view Gallery of This Property</button></span>
From what I understand I will want to use to use this function to hide the element:
document.getElementById('element').style.display = 'none';
But I am unsure how to work this into my current code. Do I add this with my current function, or is this a separate function all together?
If someone could point me into the right direction of how to code this properly I would really appreciate it.
Thank you so much,
-Kasandra
I think this is one of those exceptional cases where you want to use inline style to hide your element. This is because it takes a few seconds for the JavaScript to load. So some users may end up seeing the element when they first get on the page, then see it quickly disappear.
<img src="INITALPAGELOADIMAGE" alt="Images" id="imageReplace" class="changeImageClass" style="display: none;">
<span style="float: right; padding:2px;"><Button>Click to view Gallery of This Property</button></span>
Add an onclick attribute to your property links,
TEXT
And use the following function to show the elements
function changeImage (src, href) {
// get a reference to the DOM elements
var img = document.getElementById('imageReplace'),
link = document.getElementById('linkReplace');
// update the elements
img.src = src;
link.href = href;
// show the elements
img.style.display = '';
link.style.display = '';
}
Here's a quick demo (updated).
Using css, you can have the block have display: none; and then when you use show it will change the display to default (usually display: block;)

JS load image on click

I need to load an image, js need to get link url and print this image on screen.
But it is not working.
What is wrong with my script? what can I do to make it work and improve it?
html
<div id=img></div>
<div id=loading></div>
<a href=http://png-5.findicons.com/files/icons/1580/devine_icons_part_2/128/my_computer.png class=postmini>Open image 1</a>
<br>
<a href=http://www.iconshock.com/img_jpg/BETA/communications/jpg/256/smile_icon.jpg class=postmini>Open image 2</a>
js
$(function() {
$(".postmini").click(function(){
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
$("#img").append(I);
});
});
https://jsfiddle.net/u6j2udzb/
and this loading div, what I need to do to make it work properly?
You are missing a lot and have a lot you don't need. I have commented out where you don't need items. In particular you don't need a loading because the image will be there before they see that. However, if you do want it still, you should be loading it underneath the image you are loading. So it gets covered by the image. I can update it with that if you'd like.
What you are missing is actual code to turn the href into an image source and you are not removing the default action of the anchor tag so it doesn't try loading a new page when clicked.
$(".postmini").click(function(event){
event.preventDefault();
var element = $(this);
var I = element.attr("href");
//$("#loading").html('loading...');
//$("#loading").ajaxComplete(function(){}).slideUp();
// remove old image if it is already there.
$("#img").empty();
// create variable holding the image src from the href link
var img = $("<img/>").attr("src", I)
$("#img").append(img);
});
https://jsfiddle.net/3g8ujLvd/
You just have to insert an img tag into your "display div" on click on the link... to load the image... (btw your syntax errors are terrible... you have to use quotes for attributes^^)
like this for example :
$('.postmini').on('click',function(){
//do something
});
Check this : https://jsfiddle.net/u6j2udzb/8/
(done quickly for example)
Hope it helps
You are not running an ajax script. ajaxComplete is only fired after an ajax script completed.
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
You should ad an ajax script and than ajaxComplete will run if you registered the ajaxComplete method.
At the moment you're just placing the text from the "href" attribute on the link into the div. You need to either create an image or use the link provided as a background.
The quickest way to see this is to change make this change:
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
// $("#img").append(I);
$("#img").html("<img src='"+I+"' />");
$('.postmini').on('click',function(e){
e.preventDefault();
$('#loading').html('<img src="'+this.href+'">').children('img').one('load',function(){$(this).parent().slideUp('slow');});
});
Noticed I used on instead of click this allows you to use this.href rather than a more lengthy $(this).attr('href'). I also used .one on a child image element to find out if the image has loaded.
But I've just realised that this is useless because you want to have a loader. Ma bad.
$('.postmini').on('click',function(e){
e.preventDefault();
//best have the loader.gif showing on default before the load is complete.
var img=$('<img class="loadedImage">');
img.src=this.href;
//img.css({display:none;});//remove this if you've enter CSS .loadedImage{display:none;}
$('#loading').append(img).slideDown('slow',function(){$(this).children('.loadedImage').one('load',function(){$(this).fadeIn('slow');$(this).siblings('img[src="loader.gif"]').hide();});});
});
This method is what you're looking for. Basically you want to click the link, stop the default action of going to the link, make a new image element and set the src, make sure it's hidden before load, add the new image element to loading, slide up parent loading, check for load and fade in :)
Try and run this simple snippet
$('#myButton').click(()=>{
let imgUrl = $('#imgUrl').val();
$.get(imgUrl)
.done(() => {
$('img').attr('src', imgUrl);
$('#imgText').text('');
})
.fail(() => {
$('#imgText').text('Image does not exist');
$('img').attr('src', '');
})
})
img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Image url: <input type="text" id="imgUrl" value="https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg"><br>
<button id="myButton" type="button">click here to load image</button>
<div id="imgText"></div>
<img>

Jquery: Put variable from attribute into <p>, live() won't work [duplicate]

This question already has answers here:
Turning live() into on() in jQuery
(5 answers)
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I have been using this code to get a simple lightbox working on a site of mine.
And I tried to modify it slightly so:
a) The lightbox fades in- Done
b) The script pulls in the src attribute not the href- Done
b) I can pull in data from a custom "data-description" attribute on the <img> that is being clicked (or tapped I suppose) to a <p> in the lightbox.
Issues
With the second, when the image is first clicked, It works fine. When any other is clicked, or it is clicked again, nothing happens- I can't work out why as I seem to be doing it right?
Also, when using jQuery 1.9, live() is apparently depreciated- I was using 1.8.2 before and didn't notice until now, I have tried on() with no sucess, and being a JS beginner am puzzled as to how to fix it, this issue means that the lightbox won't close.
Almost-working-but-broken code here: http://codepen.io/hwg/pen/ybEAw - Sorry about all the comments but I find it easier that way.
JS:
$(document).ready(function() { //Document Ready
$('.inner_img').click(function(e) {
//prevent default action (hyperlink)
e.preventDefault();
//Get clicked link href
var image_src = $(this).attr("src");
// Get Description
var desc = $(this).attr("data-description");
/*
If the lightbox window HTML already exists in document,
change the img src to to match the href of whatever link was clicked
If the lightbox window HTML doesn't exists, create it and insert it.
(This will only happen the first time around)
*/
if ($('#lightbox').length > 0) { // #lightbox exists
//place href as img src value
$('#content').html('<img src="' + image_src + '" />');
// Change Description in the P tag
$('.desc').html(' '+ desc +' ');
//show lightbox window - you could use .show('fast') for a transition
$('#lightbox').fadeIn(); // Fades it in
}
else { //#lightbox does not exist - create and insert (runs 1st time only)
//create HTML markup for lightbox window
var lightbox =
'<div id="lightbox">' +
'<p>Click to close</p>' +
'<div id="content">' + //insert clicked link's href into img src
'<img src="' + image_src +'" />' +
'<p class="desc">'+ desc +'</p>' + // Adds Description from <img data-description="..">
'</div>' +
'</div>';
//insert lightbox HTML into page
$(lightbox).hide().appendTo("body").fadeIn();
}
});
//Click anywhere on the page to get rid of lightbox window
$('#lightbox').on('click', function() { //must use live, as the lightbox element is inserted into the DOM
$("#lightbox").fadeOut(); // Fades it out
});
}); // End
Thanks for any help.
EDIT: I have been shown that the live/on issue is very common, I can see where I went wrong. Thanks for the assistance on this commenters.
However, why won't my code work for the second issue?
use event delegation with on -
$(document.body).on('click','#lightbox', function() {
$("#lightbox").fadeOut(); // Fades it out
});
Demo ---> http://codepen.io/anon/pen/ywJhe
You can change
$('.inner_img').click(function(e) {
to
$(document.body).on('click', '.inner_img', function(e) {
so that events occurring after the binding will still be delegated to the new elements.

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

Categories