I found an open-source code that was perfect for my husbands website. I changed it to our liking, but it keeps giving an annoying error in the console:
Unable to get property "ownerDocument" of undefined of null reference.
In Firefox it says simply: TypeError: context is null
the error is supposedly here: jquery-1.10.2.js, line 1822 character 2
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
I think I am doing something wrong in my code, but I can't seem to say where.
Also there is a weird IE error: The contact and bio page dissappear, when I open the menu, it is there, but it only comes foreward when I select that part of the page, and then it dissappears. I don't know if it is anything to do with the above error.
It works fine on Safari, Firefox, Chrome, but most of the visitors use IE.
HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Franklin Cando - Photographe</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="description" content="Franklin Cando - Photographe" />
<meta name="keywords" content=""/>
<!--I added this as a test, since I saw somewhere that this could help-->
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta http-equiv="X-UA-Compatible" content="IE=6" />
<link rel="shortcut icon" href="/images/icons/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen"/>
<script src="js/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/cufon-yui.js" type="text/javascript"></script>
<script src="js/Quicksand_Book_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
Cufon.replace('span,p,h1',{
textShadow: '0px 0px 1px #ffffff'
});
</script>
<script type="text/javascript">
(function(i,s,o,g,r,a,m)
{
i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},
i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)0];
a.async=1;
a.src=g;
m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-
analytics.com/analytics.js','ga');
ga('create', 'UA-44223947-1', 'franklincando.com');
ga('send', 'pageview');
</script>
</head>
<body>
<div id="st_main" class="st_main">
<img src="images/album/AK9A4519.jpg" alt="" class="st_preview" id="bigImage"
style="display:none;"/>
<div class="st_overlay"></div>
<h1>
<a class="titelLink" href="http://www.franklincando.com/">Franklin Cando</a>
</h1>
<div id="st_loading" class="st_loading"><span>Loading...</span></div>
<ul id="st_nav" class="st_navigation">
<li>
<span class="st_link">Biographie<span class="st_arrow_down"></span></span>
<div class="st_about st_thumbs_wrapper">
<div class="st_subcontent">
<table>
<!--CONTENT-->
</table>
</div>
</div>
</li>
<li>
<span class="st_link">Contact<span class="st_arrow_down"></span></span>
<div class="st_about st_thumbs_wrapper" id="form_div_parent">
<div class="st_subcontent" id="form_div_child">
<div class="contactinfo" id="contactinfo_div">
<h3>Contact</h3><br/>
<!--CONTENT-->
<form id="contactForm" method="post" action="php/send_form.php" >
<!--CONTENT-->
<input class="button" type="button" onclick="validateForm()"
value="Envoyer"/>
<input class="button" type="reset" onclick="resetForm()"
value="Effacer"/>
</form>
</div>
</div>
</li>
<li class="album">
<span class="st_link">Photos<span class="st_arrow_down"></span></span>
<div class="st_wrapper st_thumbs_wrapper" id="wrapper">
<div class="st_thumbs" id="thumbs">
<!--IMAGES-->
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
JQUERY-JS
<script type="text/javascript">
$(document).ready(function() {
//the loading image
var $loader = $('#st_loading');
//the ul element
var $list = $('#st_nav');
//the current image being shown
var $currImage = $('#st_main').children('img:first');
//the facebook button - iris
var $fb = $('#fb');
$fb.hide();
//let's load the current image and just then display the navigation menu
$('<img>').load(function(){
$loader.hide();
if ($currImage.width() > $currImage.height()){
$currImage.css({"width":"100%"});
}
$currImage.fadeIn(3000);
//slide out the menu
setTimeout(function(){
$list.animate({'left':'0px'},500);
$fb.show();
},1000);
}).attr('src',$currImage.attr('src'));
//calculates the width of the div element where the thumbs are going to be
displayed
buildThumbs();
function buildThumbs(){
$list.children('li.album').each(function(){
var $elem = $(this);
var $thumbs_wrapper = $elem.find('.st_thumbs_wrapper');
var $thumbs = $thumbs_wrapper.children(':first');
//each thumb has 180px and we add 3 of margin
var finalW = $thumbs.find('img').length * 183;
$thumbs.css('width',finalW + 'px');
//make this element scrollable
makeScrollable($thumbs_wrapper,$thumbs);
});
}
//clicking on the menu items (up and down arrow)
//makes the thumbs div appear, and hides the current opened menu (if any)
$(document).on('click','.st_arrow_down',function(){
var $this = $(this);
hideThumbs();
$this.addClass('st_arrow_up').removeClass('st_arrow_down');
var $elem = $this.closest('li');
$elem.addClass('current').animate({'height':'170px'},200);
var $thumbs_wrapper = $this.parent().next();
$thumbs_wrapper.show();
});
$(document).on('click','.st_arrow_up',function(){
var $this = $(this);
$this.addClass('st_arrow_down').removeClass('st_arrow_up');
hideThumbs();
});
//clicking on a thumb, replaces the large image
$(document).on('click','.st_thumbs img',function(){
var $this = $(this);
$loader.show();
$('<img class="st_preview"/>').load(function(){
var $this = $(this);
var $currImage = $('#st_main').children('img:first');
$this.insertBefore($currImage);
if ($this.width() > $this.height()){
$this.css({"width":"100%"});
}
$loader.hide();
$currImage.fadeOut(2000,function(){
$(this).remove();
});
}).attr('src',$this.attr('alt'));
}).bind('mouseenter',function(){
$(this).stop().animate({'opacity':'1'});
}).bind('mouseleave',function(){
$(this).stop().animate({'opacity':'0.7'});
});
//hide image menu upon mouse out - iris
$list.find('.st_thumbs').bind('mouseleave',function(){
hideThumbs();
});
//function to hide the current opened menu //.css({"display":"none"}) // to hide
the bigger text boxes - iris
function hideThumbs(){
$list.find('li.current').animate({'height':'50px'},400,
function(){
$(this).removeClass('current');
})
.find('.st_thumbs_wrapper')
.hide()
.andSelf()
.find('.st_link span')
.addClass('st_arrow_down')
.removeClass('st_arrow_up');
}
//makes the thumbs div scrollable on mouse move the div scrolls automatically
function makeScrollable($outer, $inner){
var extra = 800;
//Get menu width
var divWidth = $outer.width();
//Remove scrollbars
$outer.css({overflow:'hidden'});
//Find last image in container
var lastElem = $inner.find('img:last');
$outer.scrollLeft(0);
//When user move mouse over menu
$outer.unbind('mousemove').bind('mousemove',function(e){
var containerWidth = lastElem[0].offsetLeft
+ lastElem.outerWidth() + 2*extra;
var left = (e.pageX - $outer.offset().left)
* (containerWidth-divWidth) / divWidth -
extra;
$outer.scrollLeft(left);
});
}
});
</script>
The website: www.franklincando.com
PS: really sorry about indentation. I spent a lot of time making it right in this post, and upon posting it still doesn't look like it is supposed to. I hope it is still clear.
The issue is here:
$(document)
/* ... */
.bind('mouseenter',function(){
$(this).stop().animate({'opacity':'1'});
}).bind('mouseleave',function(){
$(this).stop().animate({'opacity':'0.7'});
});
In this case, this is the document. You can't animate the opacity of the document. Change it to body instead and it should be fine.
$("body").bind('mouseenter',function(){
$(this).stop().animate({'opacity':'1'});
}).bind('mouseleave',function(){
$(this).stop().animate({'opacity':'0.7'});
});
I ended up rebuilding the project. The base code I was using was for an older version of jQuery and I added the newest libraries. I think the code clashed on that. Working fine now.
Related
I'm trying to make divs created with .createElement be draggable. It works fine with divs that are already created like below:
<div>
This can be dragged around, but outputs cannot?!
</div>
but when I create new divs with the function addElement(), it doesn't work.
In more detail here is what my code aims to do:
user inputs text -> clicks input button and the user input(s) are outputted on the screen and can be dragged.
Full code:
function addElement () {
var text = document.getElementById("input").value;
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
document.getElementById("input").value = " ";
}
$( function() {
var div = document.getElementsByTagName('div');
$( div ).draggable();
} );
div { width: 150px; height: 150px; padding: 0.5em; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input"type="text" placeholder=" text">
<button onclick="addElement()" >Input</button>
<p>Outputs:</p>
<script src="script.js"></script>
</body>
</html>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>
When you load the page, the draggable gets attached to the div element which is already loaded. But when you dynamically create a new element, the draggable is not re-attached to the new div. So, whenever you add a new div, you need to re-attach the draggable event to it:
function addElement() {
var text = document.getElementById("input").value;
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
$(function() {
var div = document.getElementsByTagName('div');
$(div).draggable();
});
document.getElementById("input").value = " ";
}
$(function() {
var div = document.getElementsByTagName('div');
$(div).draggable();
});
div {
width: 150px;
height: 150px;
padding: 0.5em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input" type="text" placeholder=" text">
<button onclick="addElement()">Input</button>
<p>Outputs:</p>
<script src="script.js"></script>
</body>
</html>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>
When you load the page, the draggable gets attached to the div element which is already loaded. But when you dynamically create a new element, the draggable is not attached to the new div. Whenever you add a new div, you need to re-attach draggable event to it.
You only run
$( function() {
var div = document.getElementsByTagName('div');
$( div ).draggable();
} );
when your app loads for the first time, therefore newly created divs are not draggable.
When you want the new divs to be draggable, you have to add $( newDiv ).draggable() to your addElement() function.
You are using $(callback), which only calls the function once when the DOM is loaded.
However, when you add new elements, they will not be made draggable since the function that does it has already run.
To make the new elements draggable too, you will need to call jQuery.draggable() on them as well after creating them.
This means, you should add newDiv.draggable() inside your function that creates the elements.
Sidenote
When using an API like jQuery, you should try to stick to it rather than the native methods to make understanding it easier, since one wouldn't have to go back and forth in their mindsets.
Subnotes
You have incorrect HTML since you have a <div> after closing both <body> and <html>, and are trying to close them again at the end. Since HTML disallows elements outside of <body>, most browsers automatically correct this mistake. However, you should format the HTML correctly yourself.
Creating jQuery-elements using $(document.createElement('div')) instead of using $('<div>') is (minimally) faster, hence I use it below
Do not add the onclick-listener in the HTML, instead, add it using JavaScript. Adding the listener inline would require the function to be exposed in the global scope, and would pollute the global namespace. Listeners do not require to be named, and can easily be added in JS, allowing to not expose the functions to the global scope.
Making your code use mostly jQuery would make it look like this:
$(function() { // Executed once DOM loaded
// Make all pre-existing 'div's draggable
$('div').draggable();
// Add the 'onclick'-listener using jQuery
$('button').click(function() {
// Creating jQuery-element this way; read about the reason in the sub-notes
var newDiv = $(document.createElement("div"));
newDiv.text($('#input').val()); // Set the text to the value of 'input'
newDiv.draggable(); // Make it draggable
$('body').append(newDiv); // Append it to the body
$('#input').val(''); // Set 'input's value to ""
});
});
div {
width: 150px;
height: 150px;
padding: 0.5em;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input" type="text" placeholder="text">
<button>Input</button>
<p>Outputs:</p>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>
I am making an offline application of a music website using JS and I am handling song queues using arrays. I added song blocks with skip buttons so users can choose which song to skip without spamming another skip button that only allows them to skip the first song of the queue. The problem is, splicing the array with the index of the selected song the users wanted to skip removes the rest of the songs after it.
Example array: ["songA","songB","songC","songD","songE"]
If the user choose to skip songC, the song queue will become ["songA","songB"] and the songC to songE will be removed, but in reality the expected outcome should be ["songA","songB","songD","songE"].
I have no idea what is wrong with the code and I have searched similar topics regarding this problem but still no results. I am still new to JS and my code's a bit rough but I'm pretty sure that's not the cause of the issue.
JS:
//function of skip buttons on song blocks
songPlaylist.addEventListener("DOMNodeInserted", function() {
iconList = document.querySelectorAll(".deleteIcon");
iconList.forEach(function(element) {
element.addEventListener('click', function() {
var nameOfSong = this.parentNode.childNodes[0].dataset.name;
var indexByName = songQueue.indexOf(nameOfSong);
var selectedBlock = this.parentNode;
if (songQueue.length == 1) {
songQueue.shift();
songPlaylist.removeChild(songPlaylist.firstChild);
var emptyMsgSpan = document.createElement("div");
emptyMsgSpan.className += "emptyMsgSpan";
var emptyMsg = document.createTextNode("Playlist is empty! How 'bout adding some music?");
emptyMsgSpan.appendChild(emptyMsg);
document.getElementById("playlistContainer").appendChild(emptyMsgSpan);
setTimeout(function() {
audioPlayer.src = "";
}, 1000);
} else {
songQueue.splice(indexByName,1); // <--- press first block output delete everything
// press any block after first deletes everything beneath it
songPlaylist.removeChild(selectedBlock);
for (var blockIndex = indexByName; blockIndex <= songQueue.length; blockIndex++) {
document.getElementById("playlistContainer").children[blockIndex].childNodes[1].dataset.index -= 1;
}
};
});
});
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<link href="https://fonts.googleapis.com/css?family=Bai+Jamjuree" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Jost&display=swap" rel="stylesheet">
<!--<div>Icons made by Roundicons from www.flaticon.com</div>-->
<title>Mue - Custom Playlist</title>
</head>
<body>
<div id="bg">
<div class="titleBar">
<button style="background: none; border: none; cursor: pointer;" onclick="location.reload(); return false;">
<span>MUE</span>
</button>
</div>
<div class="songNameDisplay">
<span id="nowPlaying"></span>
</div>
<div class="trackContainer">
<div class="btn play"></div>
<div class="audioTrack">
<div class="trackBtn"></div>
</div>
<div id="skipBtn">
<div class="triangle1"></div>
<div class="triangle2"></div>
<div class="rect"></div>
</div>
</div>
<button id="fileBtn" class="fileBtn"><span>Upload</span></button>
</div>
<audio id="audioPlayer" controls autoplay></audio>
<input type="file" id="file" />
<div id="playlistContainer"></div>
</body>
<script src="index.js"></script>
<script>
const bg = document.getElementById("bg");
window.addEventListener('scroll' , function() {
let offset= window.pageYOffset;
bg.style.backgroundPositionY = offset * 0.5 + "px";
});
</script>
</html>
Thanks in advance.
I'm at my wit's end here. I have a link on my page that is designed to load the contents of a PartialView into a <div> on my page as a draggable modal. The Javascript code to load the content into a div works, but my callback to create the modal fails with the following error:
> Uncaught TypeError: undefined is not a function
> jquery-1.8.2.min.js:19p.fn.extend.add
> jquery-1.8.2.min.js:19p.fn.extend.addBack
> jquery-1.8.2.min.js:19a.widget._getHandle
> jquery-ui-1.8.24.min.js:23a.widget._mouseCapture
> jquery-ui-1.8.24.min.js:23a.widget._mouseDown
> jquery-ui-1.8.24.min.js:23(anonymous function)
> jquery-ui-1.8.24.min.js:23p.event.dispatch
> jquery-1.8.2.min.js:19g.handle.h jquery-1.8.2.min.js:19
Code from HTML head as defined in my _Layout.cshtml file:
<head>
<meta charset="utf-8" />
<title></title>
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.8.24.min.js"></script>
<script src="/Scripts/modernizr-2.6.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.dataTables.min.js"></script>
<link href="/Content/siteV2.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="/Content/jquery.dataTables.min.css" />
</head>
Javascript code to execute that resides on my ViewPresentationSchedule.cshtml page, which is returned as a View:
<script type="text/javascript">
function showAddForm() {
$('#AddPresenterForm').load('#Url.Action("AddPresenterForm", "Pod", new { podId = pod.PodId })',
function () {
showform();
}
);
}
//fades in our help popup and makes it draggable but not resizable
function showform() {
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $('#AddPresenterForm').height();
var popupWidth = $('#AddPresenterForm').width();
$('#AddPresenterForm').css('position', 'absolute');
$('#AddPresenterForm').css('top', windowHeight / 2 - popupHeight / 2);
$('#AddPresenterForm').css('left', windowWidth / 2 - popupWidth / 2);
$('#AddPresenterForm').fadeIn('slow',
function () {
$('#AddPresenterForm').draggable();
$('#AddPresenterForm').css('display', 'block');
});
}
</script>
Div on ViewPresentationSchedule.cshtml, which is returned as a View:
<div id="AddPresenterForm">
</div>
Link to make all the magic happen:
Add Presenter
Any ideas what may be happening? I suspect that jQuery UI is not loading/initializing properly as I have .datepicker() commands on other pages that don't work as well.
After further investigation, there was something wrong with my jQuery files. I deleted them and retrieved them from a CDN and now everything works as expected.
Perhaps it has to do with where you are initializing draggable(). You could probably initialize the draggable() prior to loading the content. I assume #AddPresenterForm is hidden until the Add Presenter button is clicked, in which case it wouldn't be a problem if it is already draggable by the time it becomes visible.
If that doesn't seem to work you could use jQuery UI Modal Dialogue box which could make what you are doing a lot easier.
Here is a link to an example that seems to match what you are trying to do: http://jqueryui.com/dialog/#modal-form
I am trying to show one div at a time and scroll trough them over and over. I have modified a Fiddle I found and I got it working on fiddle, but for some reason I cant implement a simple test page with the fiddle. It simply does not scroll trough the divs.
Here is the fiddle: http://jsfiddle.net/Twistar/d6nZP/86/
And here is my implemented code:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script type="text/javascript" src="includes/headers/jquery.min.js"></script>
<script type="text/javascript">
function go() {
var visibleBox = $('#container .boxes:visible');
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) {
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000);
</script>
</head>
<body>
<div id="container">
<div class="boxes" style="display:">first box</div>
<div class="boxes" style="display:none;">second box</div>
<div class="boxes" style="display:none;">third box</div>
<div class="boxes" style="display:none;">forth box</div>
</div>
</body>
Can anyone please tell me what i am doing wrong?
I am guessing that you have a working fiddle but on your local test page its not working
your fiddle works because you got selected the default handlers from left handside dropdowns and its not working on your test page because your jquery handler is missing.
the reason is you are missing the document ready handler here:
$(function(){
setInterval(go, 1000);
});
try replacing with this one and see if helps.
I would probably simplyfy and would go with something like this: http://jsbin.com/osepim/1/
$(function() {
// hide all and show first
$(".boxes").hide().first().show();
setInterval(function(){
moveNext();
}, 1000);
});
function moveNext() {
var box = $(".boxes:visible"),
nextBox = box.next();
if(nextBox.length === 0)
nextBox = $(".boxes:first");
//hide all
$(".boxes").hide();
// show next
nextBox.fadeIn();
}
you need to wrap your javascripts code with the ready event $(document).ready() or use the short version $() and that will only excecute your codes when the page is finished loading so your codes should looks something like that
$(function(){
function go() {
var visibleBox = $('#container .boxes:visible');
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) {
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000);
});
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<style type="text/css">.boxes{display:none}</style>
</head>
<body>
<div id="container">
<div class="boxes">first box</div>
<div class="boxes">second box</div>
<div class="boxes">third box</div>
<div class="boxes">forth box</div>
</div>
<script type="text/javascript" charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function go() {
var visibleBox = $('#container .boxes:visible'); // GET THE DIV
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) { // SHOW NEXT ITEM
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000); // MS SECOND OF LOOP
</script>
</body>
</html>
I have searched high and low for an answer and have found similar examples of the problem but the answers do not apply to my scenario. The reality is I am new to this and therefore I don't have the skills to adapt the answers I have found to my problem.
The problem:
I have a Div in which when a thumbnail is clicked the Div image replaces with another image via a JavaScript/jQuery script (I am not sure exactly maybe someone could clarify). This works fine however the problem is the page scrolls back to the top and the user then has to scroll back down to see the image after it has replaced itself.
I have looked online and have found that a return false: in the JavaScript may help however I have looked and return false is already present.
The other option I have looked at using is a JavaScript cookie based solution in which a cookie is sent, and the browser scroll position is maintain by reading the cookie however I cant seem to get that solution to work, I think the issue may be caused because I am hosting locally but I may be wrong...
The third is using a PHP script but I have not found a definitive answer on this method and it also means I am going to have to learn about PHP (something I'm sure I will have to learn in time anyway).
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('.galleryicon').live("click", function() {
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
return false;
});
});
</script>
Here is the html:
<div class="cakecont">
<div id="cakebox">
<img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>
<div class="pageinfo2">
<h3>Cake Type 1</h3>
<h6>£2.00</h6>
</div>
<div class="infobox">
<h6> Description </h6>
</div>
<div class="gallerybox">
<a href="../images/cakes/babycaketop.png" class="galleryicon">
<img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>
<a href="../images/cakes/babycake1.png" class="galleryicon">
<img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
</div>
</div>
</div>
And here is a link to the working demo http://micahcarrick.com/code/jquery-image-swap/index.html
I have tried to resolve this on my own. This is the first question I have had to ask so far regarding the building of my website, all my learning and remedies to past problems have been served by Google, this one has eluded my search engine skills.
Below I have added all the html for the page in case there may be other script overriding the "new" modified JavaScript -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupcakes & Cakes for Birthday/Wedding Gift in Bournemouth Dorset - SweetVision</title>
<meta name="keywords" content="cupcakes, cake, gift, wedding, birthday, Bournemouth, Dorset" />
<meta name="description" content="For the finest Cupcakes and Cakes in Bournemouth Dorset look no further, Sweetvision specialise in baked goods for Weddings, Birthdays, Baby Showers, Easter, Halloween, Christmas" />
<meta name="robots" content="ALL" />
<meta http-equiv= "Content-Language" content="en" />
<meta name="Publisher" content="Sweet Vision" />
<meta name="Copyright" content="Copyright 2012, Sweet Vision, All rights reserved." />
<meta name="Author" content="Mark Webb for Sweet Vision - www.sweetvision.co.uk" />
<link href="../images/homepage/favicon.ico" type="image/vnd.microsoft.icon" rel="shortcut icon" />
<link href="../root/css/sweetvision.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
</script>
<script src="../js/s3Slider.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#s3slider').s3Slider({
timeOut: 4000
});
});
</script>
<script src="../js/SpryMenuBar.js" type="text/javascript"></script>
<link href="../root/css/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="sprybox">
<ul id="check_menu" class="MenuBarHorizontal">
<li>Home</li>
<li>About Us
<ul>
<li>Contact</li>
<li>News</li>
<li>Events</li>
</ul>
</li>
<li>Our Menu</li>
<li>Gallery</li>
</ul>
<div class="mainmenu">
<a href="../root/mainmenu.html">
<img src="../images/buttons/mainmenu.png" />
</a>
</div>
<div class="backbutton">
<a href="javascript:history.go(-1)">
<img src="../images/buttons/Backbutton.png" /></a>
</div>
</div> <!-- end.header --><!--end of sprybox -->
<!--end div element -->
<!-- thumbnails are links to the full size image -->
<div class="cakecont">
<div id="cakebox">
<img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>
<div class="pageinfo2">
<h3>Cake Type 1</h3>
<h6>£2.00</h6>
</div>
<div class="infobox">
<h6> Description </h6>
</div>
<div class="gallerybox">
<a href="../images/cakes/babycaketop.png" class="galleryicon">
<img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>
<a href="../images/cakes/babycake1.png" class="galleryicon">
<img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
</div>
</div>
</div>
<div class="footer">
<p>Copyright © 2012 by Mark Webb. All rights reserved.</p>
</div> <!-- end .footer -->
</div> <!-- end .container -->
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("check_menu",{imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29457683-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
You can save the current scroll amount and then set it later:
var tempScrollTop = $(window).scrollTop();
..//Your code
$(window).scrollTop(tempScrollTop);
For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:
<a
href='javascript:void(0)'
onclick='javascript:whatever causing the page to scroll to the top'
></a>
Try the code below to prevent the default behaviour scrolling back to the top of the page
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
For more information on event.preventDefault() have a look here at the official documentation.
What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:
$(document).ready(function() {
$('.galleryicon').live("click", function(e) {
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
return false;
e.preventDefault();
});
});
So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) { and you're adding the line e.preventDefault();
I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.
This is cut from wdCalendar where I modified this procedure:
function BuildDaysAndWeekView(startday, l, events, config)
....
var scrollpos = $("#dvtec").scrollTop();
gridcontainer.html(html.join(""));
setTimeout(function() {
$("#dvtec").scrollTop(scrollpos);
}, 25);
....
Without the delay, it simply did not work.
Something to note, when setting the scroll position, make sure you do it in the correct scope. For example, if you're using the scroll position in multiple functions, you would want to set it outside of these functions.
$(document).ready(function() {
var tempScrollTop = $(window).scrollTop();
function example() {
console.log(tempScrollTop);
};
});
$('html,body').animate({
scrollTop: $('#answer-<%= #answer.id %>').offset().top - 50
}, 700);