I have a button in index.html. after click on this button, I want to append an image in body section of page2. The following code only opens page2 but the rest of code doesn't work. What I am doing wrong? thanks
function ready()
{
var w = window.open("Page2.html");
w.onload = function(){
var p = document.createElement("img");
x.setAttribute("src", "ts_WWW_2016w03.jpg");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
w.document.body.appendChild(p);
};
}
Method 1:
One way to do this is by making use of query string, it could be like this:
Plunker Demo 1
page1.html
<h1>Page 1</h1>
<button id="clickMe">Open New Page</button>
<script>
document.getElementById("clickMe").addEventListener('click', ready);
function ready() {
var $s = 'http://lorempixel.com/400/200/city/2/',
$w = '400px',
$h = '200px',
//we combine the three into one string using '&' as a delimiter
$qs = $s + '&' + $w + '&' + $h;
//then we add that final string as query to the href
window.open('page2.html?' + $qs);
}
</script>
page2.html
<h1>Page 2</h1>
<script>
// we first grab page href, extract that string we injected in
// page1 which comes after the '?' mark.
// then we split the string into an array with three elements.
var a = location.href,
b = a.substring(a.indexOf("?") + 1),
qStrings = b.split('&'),
$img = document.createElement("img");
// because of how we combined the string in page 1, the first
// element of the array represents the 'src'
// the secodn elements represents the 'width' and the last
// on is the 'hight'.
console.log(qStrings);
$img.setAttribute("src", qStrings[0]);
$img.setAttribute("width", qStrings[1]);
$img.setAttribute("height", qStrings[2]);
//then we append the image
document.body.appendChild($img);
</script>
Method 2:
You can also achieve it using sessionStorage or localStorage,
IMHO this is better because the url in the address bar of page2 tab won't look like a mess and could be a better way to avoid errors comparing to method 1.
Plunker Demo 2
page1.html
<h1>Page 1</h1>
<button id="clickMe">Open New Page</button>
<script>
document.getElementById("clickMe").addEventListener('click', ready);
// we create three session keys for src, width and height
// and we set their values, then we launch page2
function ready() {
sessionStorage.setItem('$src', 'http://lorempixel.com/400/200/city/2/');
sessionStorage.setItem('$width', '400px');
sessionStorage.setItem('$height', '200px');
window.open('page2.html');
}
</script>
page2.html
<h1>Page 3</h1> back to page 1
<script>
// First, just in case a user opens page2 before clicking the button in page1,
// we check if the session item we need have been set or not, if yes we proceed
if (sessionStorage.getItem('$src') && sessionStorage.getItem('$width') && sessionStorage.getItem('$height')) {
var $img = document.createElement("img");
// we get the session values and set them as values of
// the image attributes, then we append the image
$img.setAttribute("src", sessionStorage.getItem('$src'));
$img.setAttribute("width", sessionStorage.getItem('$width'));
$img.setAttribute("height", sessionStorage.getItem('$height'));
document.body.appendChild($img);
// this is optional but it might be a good practice to
// remove the session items
sessionStorage.removeItem('$src');
sessionStorage.removeItem('$width');
sessionStorage.removeItem('$height');
}
</script>
I have through test on last version of chrome.
the x is not define: x.setAttribute.
function ready()
{
var w = window.open("Page2.html");
w.onload = function(){
var p = document.createElement("img");
p.setAttribute("src", "images/ts_WWW_2016w03.jpg");
p.setAttribute("width", "304");
p.setAttribute("height", "228");
w.document.body.appendChild(p);
};
}
ready();
Related
I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}
I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
This should get you started (starting with your original code).
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
Of course, this would be easier:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
And this would be easiest (using the file name):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
You can do this with PHP or JS. But in either case you first need to be able to programmatically determine the page number of the currently displayed page.
You mention PHP, is this WordPress or some other similar CMS?
Okay so you mentioned that this is a basic website, but we still need to be able to pull that currentPageID. We could do this a few ways, the coolest would probably be to take it from the url, so let's do that.
To get the number from the url structure you mention in comments (hostname.com/page-1.html):
// Let's first grab the url and pull just the last segment, in case there are numbers anywhere else in the url.
var url = window.location.href;
var array = url.split('/');
var lastSegmentOfUrl = array[array.length-1];
// Next, let's regex that last segment for the first number or group of numbers
var reg = /\d+/;
var currentPageID = lastSegmentOfUrl.match(r); // That's it!
// Then some basic math to get the next and previous page numbers
var previousPageID = currentPageID - 1;
var nextPageID = currentPageID + 1;
// And finally we change the href values on the next and previous <a> elements
document.getElementById('previous').href('/page-' + previousPageID + '.html');
document.getElementById('next').href('/page-' + nextPageID + '.html');
This will keep working forever assuming your url structure stays the same insofar as the last segment only has the current page number and no other numbers, and also that the next and previous anchor tags ID's don't change.
Here is a method using location.pathname and String.prototype.replace, no extra templating required!
Update Includes check that page exists before fetching.
// Check that a resource exists at url; if so, execute callback
function checkResource(url, callback){
var check = new XMLHttpRequest();
check.addEventListener("load", function(e){
if (check.status===200) callback();
});
check.open("HEAD",url);
check.send();
}
// Get next or previous path
function makePath(sign){
// location.pathname gets/sets the browser's current page
return location.pathname.replace(
// Regular expression to extract page number
/(\/page\-)(\d+)/,
function(match, base, num) {
// Function to increment/decrement the page number
return base + (parseInt(num)+sign);
}
);
}
function navigate(path){ location.pathname = path; }
var nextPath = makePath(1), prevPath = makePath(-1);
checkResource(nextPath, function(){
// If resource exists at nextPath, add the click listener
document.getElementById('next')
.addEventListener('click', navigate.bind(null, nextPath));
});
checkResource(prevPath, function(){
// If resource exists at prevPath, add the click listener
document.getElementById('prev')
.addEventListener('click', navigate.bind(null, prevPath));
});
Note that this will increment the "page-n" portion of the path, even if you are in a sub-path. It will also work for non-html extensions.
E.g.,:
mysite.com/page-100/resource => mysite.com/page-101/resource
or
mysite.com/page-100.php => mysite.com/page-101.php
Hi im building a slider using jquery tools.. here is my code http://jsfiddle.net/SmW3F/5/
Anyway, the problem is when you over the image is updated (the Main image) so each thumb update the main image on hover.
The problem is the title is just working for 1st item.. all other items are not updating the title..
here is this part of the code
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
var count = 0;
var scroll_count = 0;
setInterval(function(){
count++; // add to the counter
if($(".items img").eq(count).length != 0){
console.log(count);
$(".items img").eq(count).trigger("mouseover");
if(count % 5 === 0)
{
I found a couple of issues with your script, but first you have invalid markup in your page since you have multiple <div> elements with the same ids of tbtit and tbdescp. Id attributes should be unique in a HTML page so should change those to classes instead.
Now in your script you need to change the part where you retrieve the values of the title and the description of the image that is hovered to reference the sibling elements:
//THIS
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
//SHOULD NOW BE THIS
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
Finally when you update the text for your main image you want to set the content for your <h4> and <p> tags and not replace them completely, so use .text()
//THIS
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
//SHOULD NOW BE THIS
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?
function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });
Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load
I'm trying to get an user input image to refresh say every two seconds. The javascript gets user input for an URL and the javscript adds it to the page. Then the images loaded need to refresh every 2 seconds but i can't get it to refresh properly without refreshing the whole page or reloading from the cache:
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
div.className="imageWrapper";
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}
setInterval(function(){
$('img').each(function(){
var time = (new Date()).getTime();
$(this).attr("src", $(this).attr("src") + time );
});
}, 2000);
any ideas?
When you need to force reload the resource, you have to add a dymmy queryString at the end of your url:
<img id="img1" src="myimg.png?dummy=23423423423">
Javascript:
$('#img1').attr('src','myimg.png?dummy=23423423423');
and change the dummy value for each refresh
Your premise seems good, not sure why it isn't working. Why mixing and matching jQuery with non-jquery? This is a modification of your code, but it is a working example. You should be able to adapt it for your purpose.
http://jsfiddle.net/zr692/1/
You can create elements via jQuery easily. See the modified getImg function I created. Ia also switched from attr to prop which is the recommended means of accessing the src attribute in jQuery 1.7+.
function getImg() {
var url = 'http://placehold.it/300x300/123456';
var $div = $('<div />');
var $img = $('<img />', { src: url });
$div.append($img);
$('body').append($div);
}
getImg();
var interval = setInterval(function() {
$('img').each(function() {
var time = (new Date()).getTime();
var oldurl = $(this).prop('src');
var newurl = oldurl.substring(0, oldurl.lastIndexOf('/') + 1) + time.toString().substr(7, 6);
$('#output').html(newurl);
$(this).prop('src', newurl);
});
}, 2000);
Put the image in a container as:
<div id="container"><img src=""../> </div>
then simply update the content of the container as:
$('#container').html('<img src="newSource"../>');