This is my first ever question here so please bear with me (also new to programming) I will try my best to explain as clearly as I can. Basically I want to show the div content in random order everytime the page is loaded, this question has already been asked before and I have come across some answers to this but most of them are quite complicated for me. But I found a very simple answer ( Random Div Order on Page Load )
that I tried but I am not sure why won't it work for me, may be it's a little outdated?. I am pasting the code below to visualise for you lot, here are the divs in the html content that need to be randomised:
<div class="story-container">
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
</div>
<div class="story-container">
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
I may add more 'story-container' class divs in the future.
Below is the script that I got from the post given in the link I provided above (I replaced the target class with my own class 'story'):
<script>
var cards = $(".story");
for (var i = 0; i < cards.length; i++) {
var target1 = math.floor(math.random() * cards.lenth - 1) + 1;
var target2 = math.floor(math.random() * cards.lenth - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
</script>
I have tried using this code javascript code within the same html page, in the header as well as at the end of body part. I also tried saving it externally and linked to it from within my html page but no luck.
My jQuery link/version is as follows:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3
/jquery.min.js"></script>
I import this jQuery code before running the js script to randomise the divs.
Not sure where things are going wrong, any help will be greatly appreciated, thank very much in advance guys!
[PROGRESS]
Thank you very much guys for your prompt replies and detailed guidance, #Hill #fermats_last_nerve #jritchey #Quiver, although you fixed the code but still it is not working in my browser which is really strange because it works perfectly in jsfiddle, codepen and plunkr. If it is working in online tools it should work in my browser as well.
I am using WAMP as a server to test my php pages on Windows 10, I normally use Firefox browser but I have test this code on Microsoft Edge as well but no joy.
Thank you again for taking time to help me with this.
I debugged your code in this codepen. Basically you had 3 errors
There are typos in your definitions for target1 and target2
cards.lenth should be cards.length
The variable cards: var cards = $(".article") is selecting all elements with the class "article", but you don't have any elements with that class, I assume you mean var cards = $(".story")
Make sure you capitalize Math when you use it.
(EDIT) Looks like someone edited your post to have the correct class in the selector so #2 no longer makes sense in light of the new edited question but I'll leave it in case you do not notice the edit for whatever reason.
I've noticed a few typos in your code. Replace your jQuery with the code below and it should work as it does in this jsfiddle.
var cards = $(".story");
for (var i = 0; i < cards.length; i++) {
var target1 = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
Related
I have a parallax scrolling website which works via section ID's. I have animations on each of the sections but only want them to activate when the section is in the viewport. I currently have the following, which doesn't seem to be working. I'm fairly new to jquery/javascript so any help would be appreciated!
function paintLine(){
$('#3-Backup-3').lazylinepainter({
"svgData": svgData,
'ease': 'easeInOutQuad',
'strokeCap': 'square'
}).lazylinepainter('paint');
}
var element_position = $('#backup-section-3').offset().top;
$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(_scroll_pos > scroll_pos_test) {
paintLine();
}
});
<!-- Backup 3 -->
<div data-anchor="backup-section-3" class="section backup-section-3">
<div class="float-left">
<div id="backup-nav">
<p onclick="openSideNavGreen()" class="nav-section-title">Backup</p>
</div>
<div>
<p class="backup-text-title">Methods</p>
<p class="backup-text">No surprises here then: tape as a primary backup method remains at an all-time low of 3%. This is the first year it hasn’t fallen – possibly indicative of how stubborn some legacy systems (often populated with static compliance data) can be. I wouldn’t be surprised to see similar figures next year.<br><br>We did see a drop in the prevalence of combined disk/tape solutions, with a new option, External Hard Drive/USB, seeming the preferred choice instead.</p>
</div>
</div>
<div class="float-right">
<div id="3-Backup-3"></div>
</div>
</div>
$('#backup-section-3').offset().top; refers to an element with an ID of backup-section-3 which you don't seem to have in your HTML markup. Try giving the element that you're referring to an ID of backup-section-3 and see if that resolves your issue.
id needs the start with alpha character. put any alpha char in front of the 3 in your javascript and html and it will work.
I am trying to create a very simple image slider. As simple as it gets but the way I'm doing it I'm having to enter too many combinations.
This is what I've got:
<script>
$(document).ready(function(){
$('#1').show();
$('#2').hide();
$('#3').hide();
$("next-btn").click(function(){
$("#1").hide();
$("#2").show();
});
});
</script>
</head>
<body>
<div id="slider">
<div id="1" class="slide"><img src="slide-image-1" alt="" /></div>
<div id="2" class="slide"><img src="slide-image-2" alt="" /></div>
<div id="3" class="slide"><img src="slide-image-3" alt="" /></div>
</div>
<div id="previous-btn">Previous slide</div>
<div id="next-btn">Next slide</div>
As you can see by the jquery code, the way I'm going i'll have to enter different onclick's depending which image is hidden etc..
How can I change this so it can just go to the next or previous div and show it when either buttons are clicked without having to add too many combinations?
This code should work OK (tested). I hope you will get the idea :).
<script>
var active = 0;
var n = $('#slider div').length; // number of divs...
$(document).ready(function(){
showElement(1);
$("#next-btn").click(function(){
if (active < n) showElement(active + 1);
});
$("#previous-btn").click(function(){
if (active > 1) showElement(active - 1);
});
});
function showElement(id) {
$('#slider div').hide();
$('#' + id).show();
active = id;
}
</script>
active stores the number of element that is showed. When you show something else, you hide everything, and show only the one you need. n is used to store maximum number of elements so you will not get out of scope.
By the way this is not the most memory efficient solution, but it is really simple to modify it and it is really flexible. To be honest, you should track which slide is showed, which is hidden, and hide only the one that is showed, and show only the one that You need. But if there are only few slides (100?), the performance gap wont be a problem here, while the clarity of code and future expandability is much better here.
Also if something will go wrong in the future, every time user clicks something, the showElement function will repair it: hiding everything, and showing only the one you need.
Take a look on a working solution under this link: http://codepen.io/anon/pen/XbPogg
BTW: You can add more slides (id = 1, 2, 3, 4, 5, 6, ...) in your html markup, and this script will work without of any changes.
I'm sure this is a pretty common question around here but after lots of research I can't seem to find an answer to my question.
So just a little warning; I'm really new into javascript and jQuery etc.
To the question! I'm trying to apply two images (It's img's that looks like buttons :P) which you click on and it scrolls to the "next" paragraph or div.
So to get an overview of how it looks, here' a part of the HTML:
<div id="scrollbuttons">
<img id="prev" src="pics/prev.png"></img>
<img id="next" src="pics/next.png"></img>
</div>
Also:
<div id="work">
<p class="maintext">blabla</p>
</div>
<div id="gallery">
<p class="maintext">blabla</p>
</div>
<div id="project">
<p class="maintext">blabla</p>
</div>
<div id="finish">
<p class="maintext">blabla</p>
</div>
So what I'm trying to create is when you click on "next", the page should smoothly and automatically scroll to firstly, "work", then to "gallery" etc.
And when you press "prev", the page should again smoothly and automatically scroll back to the previous point.
I have the latest jQuery version and I'd like to not install plugins if it's not absolutely needed.
So I hope this is enough info to get some help, I'd really appreciate it since I'm really new to JS.
Thanks in advance
/Emil Nilsson
Here you go, this could probably be done a little more efficiently but it's dynamic and it works. Click the buttons to go forward and backward. FYI I added a mutual class called section to all of your content divs
JSFIDDLE
var Section = "start";
$("#next").click(function(){
if(Section == "start"){
var nextSection ="work";
}else{
var nextSection = $("#"+Section).next(".section").attr("id");
}
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
$("#prev").click(function(){
var nextSection = $("#"+Section).prev(".section").attr("id");
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
maybe you need something like this
http://jsfiddle.net/urUFK/
the img would be inside of the anchor like this (semantics and W3C validation):
<img id="prev" src="pics/prev.png"></img>
on my version you just need to define the first element and the div id's
I have a fairly complicated problem.
The usual markup (no problems here):
<div class="wrapper">
<div class="title"> bla bla... </div>
<div class="content"> ...content... </div>
</div>
The "twisted" markup:
<div class="wrapper">
...content... </div>
</div>
As you can see the opening tag for div.content is missing. Unfortunately I have no control over the output within .wrapper :(
So, my question is: how can I detect if div.title is present, and if not - insert <div class="content"> (not the .title) after div.wrapper ?
I'm aware how to do this with jQuery, but I need a pure javascript solution because with jQuery you get a small "delay" before the layout gets fixed. Any ideas?
There is a fair bit more code without jQuery.
var divs = document.getElementsByTagName('div'),
foundTitleDiv = false;
for (var i = 0, divsLength = divs.length; i < divsLength; i++) {
if (divs[i].className.match(/\btitle\b/)) {
foundTitleDiv = true;
break;
}
}
if (foundTitleDiv) {
var wrapper = document.createElement('div');
wrapper.className = 'content';
var div = divs[i];
wrapper.appendChild(div.cloneNode(true));
div.parentNode.replaceChild(wrapper, div);
}
It works!
Place this at the bottom of your script, or you can wait for the entire window loaded with window.onload = function() { } or research onDOMReady events.
Whilst this answers your question, the fact you have invalid HTML (the extraneous </div>) may make this solution invalid.
Well, JQuery is pure Javascript, but with JQuery there's a lot more Javascript for the browser to parse, that might be why you are experiencing some delay. I don't know exactly how you would go about fixing this with Javascript, because you are outputting invalid HTML. which will be interpretted differently by different browsers. The correct thing to do would be to output proper HTML by the use of server side code such as PHP, or ASP.
Perhaps you can fix it on the server before sending it by searching for and, if it is missing, add it. If you can't fix it on the server, then you can do it with inline javascript, but you will need to add the content as a javascript variable, parse it, then write it out.
Here's an example (FYI, I know the RegEx is wrong, but figured it got the point across ok).
<div class="wrapper">
<div class="title"> bla bla... </div>
<script type="text\javascript">
var content = "<div class="content"> ...content..."
if (!content.match(/<div class="content">/))
content = "<div class="content">" + content;
document.Write(content)
</script>
</div>
</div>
I have two image swap functions and one works in Firefox and the other does not. The swap functions are identical and both work fine in IE. Firefox does not even recognize the images as hyperlinks. I am very confused and I hope some one can shed some light on this for me. Thank you very much in advance for any and all help.
FYI: the working script swaps by onClick via DIV elements and the non-working script swaps onMouseOver/Out via "a" elements. Remember both of these work just fine in IE.
Joshua
Working Javascript in FF:
<script type="text/javascript">
var aryImages = new Array();
aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg";
aryImages[2] = "/tires/images/mich_prim_mxv4_tread.jpg";
aryImages[3] = "/tires/images/mich_prim_mxv4_side.jpg";
for (i=0; i < aryImages.length; i++) {
var preload = new Image();
preload.src = aryImages[i];
}
function swap(imgIndex, imgTarget) {
document[imgTarget].src = aryImages[imgIndex];
}
<div id="image-container">
<div style="text-align: right">Click small images below to view larger.</div>
<div class="thumb-box" onclick="swap(1, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" width="75" height="75" /></div>
<div class="thumb-box" onclick="swap(2, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" width="75" height="75" /></div>
<div class="thumb-box" onclick="swap(3, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" width="75" height="75" /></div>
<div><img alt="" name="imgColor" src="/tires/images/mich_prim_mxv4_profile.jpg" /></div>
Not Working in FF:
<script type="text/javascript">
var aryImages = new Array();
aryImages[1] = "/images/home-on.jpg";
aryImages[2] = "/images/home-off.jpg";
aryImages[3] = "/images/services-on.jpg";
aryImages[4] = "/images/services-off.jpg";
aryImages[5] = "/images/contact_us-on.jpg";
aryImages[6] = "/images/contact_us-off.jpg";
aryImages[7] = "/images/about_us-on.jpg";
aryImages[8] = "/images/about_us-off.jpg";
aryImages[9] = "/images/career-on.jpg";
aryImages[10] = "/images/career-off.jpg";
for (i=0; i < aryImages.length; i++) {
var preload = new Image();
preload.src = aryImages[i];
}
function swap(imgIndex, imgTarget) {
document[imgTarget].src = aryImages[imgIndex];
}
<td>
<img name="home" src="/images/home-off.jpg" alt="Home Button" border="0px" />
</td>
Both your examples work for me, though they're pretty unappealing examples of ancient Netscape 3-era coding.
var aryImages = new Array();
aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg";
Arrays are 0-indexed. Currently your loop will try to access aryImages[0] and get an undefined, which is will try (and fail) to preload. There is very rarely any use for the new Array constructor today. Instead use array literals:
var images= [
'/tires/images/mich_prim_mxv4_profile.jpg',
'/tires...
];
also:
document[imgTarget].src = aryImages[imgIndex];
We don't do that, or <img name> any more. In preference, give the image an id attribute and access it with document.getElementById().
Otherwise this causes all sorts of problems when image names clash with document properties and other named items on the page. Maybe you've got a name clash problem, something else called “home” in part of the document we can't see. Though if “does not even recognize the images as hyperlinks” means you aren't getting the pointer changing over the links or showing the link address, I suspect what you've actually got is a layout problem in code we can't see here, where you've accidentally positioned another element over the top of the nav so it can't be clicked on.
Anyway, it's poor for manageability, usability and accessibility to be loading images into an element like this. Use normal links to the images (so they work without JavaScript) and add progressive-enhancement JS on top, eg.:
<style type="text/css">
.thumb { display: block; }
.thumb img { width: 75px; height: 75px; border: none; vertical-align: top; }
</style>
<a class="thumb" href="/tires/images/mich_prim_mxv4_profile.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" alt="" />
</a>
<a class="thumb" href="/tires/images/mich_prim_mxv4_tread.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" alt="" />
</a>
<a class="thumb" href="/tires/images/mich_prim_mxv4_side.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" alt="" />
</a>
<img id="thumbshow" src="/tires/images/mich_prim_mxv4_profile.jpg" alt="" />
<script type="text/javascript">
// Bind to links with thumb class
//
for (var i= document.links.length; i-->0;) {
if (document.links[i].className==='thumb') {
// Preload main image
//
var img= new Image();
img.src= document.links[i].href;
// When clicked, copy link address into image source
//
document.links[i].onclick= function() {
document.getElementById('thumbshow').src= this.href;
return false;
}
}
}
</script>
Similarly, most people do simple rollovers with CSS background images these days. If you use CSS Sprites, you don't even need two separate images, so no preloading or JavaScript of any kind is necessary.
Check Firebug for errors - the Console will tell you whether it's encountering any JS errors, and the Net panel will tell you whether any requests failed.
Why not put the events on the images instead of the links and see if that helps?
Like:
function swap(el, imgTarget) {
el.src = aryImages[imgIndex];
}
and
<img name="home" src="/images/home-off.jpg" alt="Home Button" border="0px" onMouseOver="swap(this, 'home')" onMouseOut="swap(this, 'home')" />
Just checked up on this. If you are using XHTML, it may not be the JavaScript that is corrupt, but your markup: XHTML needs tags and attributes to be specified in lowercase. I assume, that IE in its much-to-desire standards support perhaps partially ignores this, and evaluates your latter example as you think it should. But Firefox, which, you know, is much more standards compliant, may treat this as an improperly formatted attribute and ignores it.
Like:
<div onclick="swap(1, 'imgColor')"></div> <!-- Should work -->
<a onMouseOver="swap(1, 'home')"></a> <!-- May not work -->
Note, that this may not be the solution at all, just a possible issue.
Bobince made many very well thought out and proper suggestions to correct and enhance my code. For that I am very grateful. He suggested that because the links were not being recognized that I probably had an element that was covering over the menu. He was 100% correct. The header DIV below the menu had a height set to "auto" which caused it to cover from the top of the document down to the bottom of the header. This covered the menu and FF would not allow access to the links below it. I made a quick adjustment to the height and added a top margin for correct placement and now my menu is able to be accessed. I thought I was going crazy when I was not getting any JS errors in Firebug. The thought never crossed my mind to check for an overlapping element. Thanks a MILLION Bobince!!!
Thank you to all for your suggestions and help.