Imageslide with jQuery (Maybe with PHP) - php

Okay, so I have my div tag here and its css style 'background' is set to default.
For example
<div id="slideimage" style="background:url(01.jpg);width:xxpx;height:xxpx;"></div>
And I have my next button
Next
So I want to happen when I clicked on the Next button, the background style of #slideimage will change into 02.jpg. I tried searching with google but it seems it's not functioning properly.
That's all. Thanks in advance.

jsBin demo
var images = [
'01.jpg',
'02.jpg',
'03.jpg'
];
var iN = images.length;
var i = 0;
function changeImage(){
$('#slideimage').css({background: 'url('+images[++i % iN]+')'});
}
$('#next').click( changeImage );
Create an array of images, a var 'index counter' (i) and get the number of images in array (iN)
than you can easily toggle your images doing this math using Modulo: ++i % iN

Did you try this javascript:
function nextImage() {
$('#slideimage').css("background", "url(02.jpg)");
}
Here is a slightly more robust demo: http://jsfiddle.net/gQQBL/

Related

How to create input number

How to create an input type number using this format?
Example :
when I start writing this number 1000, it should be generated to 1'000.
Example 2: 10000 to 10'000
I think this is it.
$(document).ready(function(){
$('#num').keyup(function(){
var numbers = $(this).val().replace("'","");
var newNum = "";
var digitCount = 0;
for(var i = numbers.length-1; i>=0; i--){
if(digitCount==3){
newNum+="'";
digitCount=0;
}
newNum += numbers.charAt(i);
if($.isNumeric(numbers.charAt(i)))
digitCount++;
}
$(this).val(newNum.split("").reverse().join(""));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<input type="text" id="num">
i'm using this plugin to make the number field auto masking. Very easy to use. Try this one. Give feedback if you can't implement it.
Jquery number masking plugin repository
Examaple usage. After download plugin file, add this code into your js section code.
$('selector_element_to_mask').number(true, 0);
Try this It will surly help you:
var num = 1000000;
console.log(formatNumber(num))
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1'")
}
DEMO with textfield
http://jsfiddle.net/65y2bbrm/1/
I think you are looking for input masking posting a similar question though a bit different but I am sure it will point you in the right direction.
javascript or jquery Input text number only and auto masking

Change the background image of a div depending on which link is selected in the navigation

i'd like to change the background image of a div depending on wich link is selected in my navigation!
exemple :
let's say I have a menu item called :
#nav li.menu-item-59
when the link is selected it changes to
#nav li.menu-item-59.selected a
I'd like that whenever one of the menu item is selected the background image of the div footer change to a different file...
I've read some articles about sibling operators but can't seem to make it work and I'm not sure it is the best way to go ..
can anyone help?
thanks ! :D
It looks like you're using JS to add the class of selected to the menu. At the same time you're adding that, also add the the menu item name to the footer. something like:
var menuName = $(this).attr('id');
$('.footer').addClass(menuName);
Then in your css for the footer, add the class to the end of the element:
.footer.menu-item-59 {
// background goes here
}
based on your fiddle below, try:
$(window).scroll(function(){
for(var i = 0; i < sections.length; i++)
if($(window).scrollTop() +5 >= sections[i].top &&
$(window).scrollTop() <= sections[i].bottom){
sections[i].link.addClass('selected')
.siblings().removeClass('selected');
var selection = 'selected' + i; // new stuff starts here
$('footer #flag').removeAttr('class');
$('footer #flag').addClass(selection);
}
});
I don't know about sibling operators but this might work...
save all the images in one place.
give all links the same class. for this example ive used 'yourmenuclass'.
then query the document and listen for which one has been clicked.
then in the switch statement to assign a different image, depending on which one has been clicked.
function init() {
[].forEach.call(document.querySelectorAll('.yourmenuclass'), function (el) {
el.addEventListener('click', change);
});
function change() {
if (this.id == 'firstlink') {
var back = document.getElementById("footername");
back.style.backgroundImage =" url('http://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Ferns02.jpg/220px-Ferns02.jpg')";
}
if (this.id == 'secondlink') {
var back = document.getElementById("footername");
back.style.backgroundImage ="url('http://www.dailyshame.co.uk/wp-content/uploads/2012/09/badger.jpg')";
}
}
}
onload = init;
if you are using simple anchors then this may not work, but should be fine for buttons or image inputs.
js fiddle

Php countdown, make the div change width for every day

Hey i have made a countdown, but what i want is a div that change width after the day.
Let's say there is 150 days back to someday, then i want the div to be 150px in width. Is this possibel? I have seach all over the web.
it's simple. store start date and update div via counting difference with now. Every 150 days re-store start date.
here's some pseudocode
var start=17/01/2013 //stored date
func countDifference(){
return differenceIs=now()-start+1;
}
func setWidth(){
div.width=countDifference();
}
For a purely php method, you could assign a class to the div based on the number of days, but then you'd need a css style specified for every single possible width.
It would be better to do it via javascript - Sugar's answer contains a basic method.
You could also use the css method in jQuery to change a css width attribute.
http://api.jquery.com/css/
You can do one thing like given below..
<div id="test" style='background-color:red;color:white;display:block;width:150px;'>asdasdsdasda</div>
<script>
$(document).ready(function(e){
var today = new Date();
var startday = new Date('01/15/2013');
var width = 150;
var diff = DateDiff(new Date(today),new Date(startday));
diff = parseInt(diff);
var val = parseInt(parseInt(diff) / parseInt(width));
if( val >= 1 ){
diff = parseInt(parseIn(diff) - parseInt(width * val));
}
var now_width = width - diff;
$('#test').css('width' , parseInt(now_width));
function DateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime();
return (datediff / (24*60*60*1000));
}
});
</script>
Please check url given below
JsFiddle Example
I hope it will be helpful for you.
thanks

change input button style using javascript on click

I wanted to change the style of the button I'm using every time I clicked that button and together change it's text. Problem is I wanted to do it using and external javascript which I'm not that familiar with it's syntax. To elaborate what I wanted to do is to have a button having a text displaying like: Very Good, Good, Moderate, Failed. Each of the text has it's own assigned gradient color using CSS let's say a gradient of Green for Very Good, Yellow for Good, Orange for Moderate and Red for failed. Tried searching for it but I only landed on an irrelevant posts. What I think is that I need to make a button with on click and everytime I click the javascript will add int values from 0 and reset back to 0 after it reaches 3. then I think I can use case for the css class assigning like this.style="failed" Well I don't know if this is possible.
UPDATE:
After doing some research I've managed to do something about the changing texts (using javascript alone) but not yet the class part since I think the class is a keyword in javascript. here's my script so far:
function buttonChange(){
var button = document.getElementById("stats");
switch (button.value)
{
case "Very Good":
button.value="Good";
break;
case "Good":
button.value="Moderate";
break;
case "Moderate":
button.value="Failed";
break;
default:
button.value="Very Good";
}
}
now the problem is the style. :)
Using jQuery your code could look something like this:
var values = new Array('Very Good', 'Good', 'Moderate', 'Failed');
var colors = new Array('lime', 'yellow', 'orange', 'red');
$('#rate').click(function() {
// current index is stored in data attribute
var idx = $(this).data('value') + 1;
// last value was selected -> go back to first one
if (idx >= values.length) {
idx = 0;
}
// update data attribute with current index
$(this).data('value', idx);
// update button text
$(this).val(values[idx]);
// update button background color
$(this).css('background-color', colors[idx]);
});​
See this FIDDLE.
have a look at this:
Change an element's class with JavaScript
I think that your CSS should have all the styles for gradients and stuff like this:
.VeryGood {//gradient for very good
}
.Good {//gradient for good
}
.Moderate {//gradient for moderate
}
.Failed { //gradient for failed
}
and then, use this javascript and html :
<script type="text/javascript">
var i = 1; //change to 0 if element dosen't need to have any class by default
var classArray = new Array();
classArray[0] = 'VeryGood';
classArray[1] = 'Good';
classArray[2] = 'Moderate';
classArray[3] = 'Failed';
function changeClass()
{
document.getElementById("MyElement").className = classArray[i];
i++;
if(i>=3){
i=0;
}
}
</script>
...
<button onclick="changeClass()">My Button</button>
now, the array key i increases every time the button is clicked, so by default, you can have your element's class as VeryGood, and every time the button is clicked, it advances to next class, so after VeryGood comes Good then Moderate then Failed, ithe it resets itself to VeryGood. hope this is what you are looking for :)
Here is a jQuery solution to cycle through the button text and the background colour for the four states:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var states = ['Very Good', 'Good', 'Moderate', 'Failed'];
var colors = ['green', 'Yellow', 'orange', 'red'];
var index = 0;
$('body').on('click', '#button', function(){
index = ++index%4;
$("#button").html(states[index]);
$("#button").css('background-color',colors[index]);
});
});
</script>
</head>
<body>
<button id="button" style="background-color:green"; type="button">Very Good</button>
</body>
</html>
Note the modulus (%) operator which simplifies the circular increment of 'index' from 0 to 3.

Using JavaScript to show and hide PHP echoed XML data

I'm using PHP to echo out 50 video id's from an XML file. I use the video id's to embed 50 YouTube videos into my website. This works fine but I need to isolate the videos two at a time. I don't want the user to see all fifty videos at once. I want them to see two, then click next, see another two, then maybe click back, etc. etc.
Here's what I have so far:
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
while ($i < 49) {
$title = (string) $xml->query->results->item[$i]->title;
$videoid = (string) $xml->query->results->item[$i]->id;
$explanation = (string) $xml->query->results->item[$i]->explanation;
$i = $i + 1;
echo $title."<br />";
echo '<iframe width="400" height="225" src="http://www.youtube.com/embed/'.$videoid.'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>';
echo $explanation."<br /><br />";
}
So I think the best thing to do is echo all fifty items to the page inside divs labeled 0 to 49...then use JavaScript to hide all divs except 0 and 1 until you click a next button and it switches to hiding everything except 2 and 3...and so on...
But I'm not sure how to do that in JavaScript/jQuery. I think using .show() and .hide() would work but I'm not sure of the syntax.
You can use the following HTML structure:
Previous videos
<div class="video-row active">
<!-- First couple videos -->
</div>
<!-- Loop through all videos, writing the other rows -->
<div class="video-row">
<!-- Last couple videos -->
</div>
Next videos
Note: Use the active class only in the first video row to show them by default on the page load.
With CSS, hide all .video-row (using: display:none;) and show only .video-row.active (using: display:block;).
Finally, use the following Javascript (jQuery needed) to navigate between video rows:
jQuery('.prev-video-row').click(function (event)
{
event.preventDefault();
var prev = jQuery('.video-row.active').prev();
if (prev.length)
{
jQuery('.video-row').removeClass('active');
prev.addClass('active');
}
});
jQuery('.next-video-row').click(function (event)
{
event.preventDefault();
var next = jQuery('.video-row.active').next();
if (next.length)
{
jQuery('.video-row').removeClass('active');
next.addClass('active');
}
});
Honestly speaking, I don't think it's great to have 50 videos embedding in a page - regardless of visibility or not; simply because they will be processed by the browser despite not being visible. (Feel free to correct me if I'm wrong, but the browser is going to see, and process, the whole DOM - and just apply the styles to the "hidden" bits.)
Gustavo Straube has given a really good answer on how to do this if you want to have 50 elements in the DOM despite the effects it may have on both browser and bandwith.
I'd probably go for something more along the lines of parsing the XML, storing all the data as JSON then dynamically updating the DOM with jQuery from HTML supplied with a templating framework like Mustache.js.
/* Generate JSON */
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
$json = array();
while ($i < 49) {
$arr['title'] = (string) $xml->query->results->item[$i]->title;
$arr['videoid'] = (string) $xml->query->results->item[$i]->id;
$arr['explanation'] = (string) $xml->query->results->item[$i]->explanation;
$json[] = $arr;
}
echo json_encode($json);
Then, in your markup have something like the below, just to initialise your first x videos - in this example 10..
$(document).ready(function(){
var template = '{{$title}}<br /><iframe width="400" height="225"'
+ 'src="http://www.youtube.com/embed/{{$videoid}}?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>'
+ '{{explanation}}<br /><br />';
var html = '';
var i=0;
for(; i<10; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
Next up have an anchor (in this example #next) to get the next 10 videos..
$('#next').click(function(){
/* template, i and json are still in scope! */
var j = i+10;
for(; i<j; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
});
The advantage of this is it's also easy to do a previous anchor...
$('#prev').click(function(){
/* template, i and json are still in scope! */
var j = i -10;
i -= 20; //10 for the current page, 10 for the start of the previous page
for(; i<j; i++){ //rebuild div content of previous page
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html);
});
Just to re-iterate, this is an alternative solution - I've suggested it as using JSON is a little bit more lightweight and more flexible than XML, and it also removes the requirement for having 50 DOM elements that aren't in use at one time. There may be a reason you've chosen the implementation that you have, but it's not the implementation I would take if I was given this problem!
For html like:
<div id="section0"></div>
Your jquery would look like:
$(document).ready(function() {
$('#section0').show();
$('#section1').show();
$('#nextButton').click(function(e){
e.preventDefault();
$('#section0').hide();
$('#section1').hide();
$('#section2').show();
$('#section3').show();
return false;
}
});
And so on...

Categories