jQuery: Changing div ID not working - javascript

I'm back already and google-fu has brought me nothing.
I'm trying to make a sort of image gallery and i need to reset the divs dynamically on my slider but I'm having no luck, here's the process:
click 'left'
left div moves forward.
central divs ID gets called 'left' and vice versa, (using a temp ID to stop two divs having the same ID)
the css is reset as if it never happened except for the image being different.
My problem is that they seem to be resetting completely to their original state, as if the ID change never happened, any ideas?
Here's the JSFiddle
and here's the offending code:
$('.navigationLeft').click(function() {
console.log("yay");
$( '#left' ).animate({
marginLeft: selWidth
}, 500, "linear", function() {
// Animation complete.
$( '#center' ).attr('id', 'temp');
$( '#left' ).attr('id', 'center');
$( '#center' ).attr('id', 'left');
$( '#left' ).css('width', '900px');
$( '#left' ).css('height', '400px');
$( '#left' ).css('overflow', 'hidden');
$( '#left' ).css('position', 'relative');
$( '#left' ).css('left:', '-900px');
$( '#left' ).css('overflow', 'hidden');
$( '#left' ).css('z-index', '2');
$( '#center' ).css('width', '900');
$( '#center' ).css('height', '400');
$( '#center' ).css('position', 'absolute');
$( '#center' ).css('overflow', 'hidden');
$( '#center' ).css('z-index', '1');
});
//reset positions and change images
});

</img> tag is not a valid tag cause images don't have a closing tag.
Also, jQuery is much more fun that you might think!
My suggestion is to not create <img> tags at all, let JavaScript do it for us, we're using an Array of images URL, after all.
Instead of jQuery's .animate(), use CSS transition!
jQuery(function($) {
const gallery = {
one: [ // (P.S: In HTML use data-gallery="one")
'http://placehold.it/900x400/0bf/fff&text=1',
'http://placehold.it/900x400/f0b/fff&text=2',
'http://placehold.it/900x400/bf0/fff&text=3',
'http://placehold.it/900x400/b0f/fff&text=4',
], // you can add more name:[] sets for other galleries
};
$('[data-gallery]').each(function(i, gal) {
const name = $(gal).data('gallery');
if (!Object.prototype.hasOwnProperty.call(gallery, name)) return;
const $slides = $(gallery[name].map(url => $('<img>', {src: url})[0]));
const tot = $slides.length; // Store how many images we have
let c = 0; // Current slide Counter
$('.slides', gal).append($slides); // Append created slides
$(".prev, .next", gal).on('click', function() {
c = ($(this).is('.next') ? ++c : --c) < 0 ? tot - 1 : c % tot;
$slides.css({
transform: `translateX(-${c*100}%)`
})
});
});
});
/*QuickReset*/*{margin:0;box-sizing:border-box}html,body{min-height:100%;font:14px/1.4 sans-serif;}
/* Gallery */
[data-gallery] .slides {
display: flex;
position: relative;
overflow: hidden;
height: 170px;
}
[data-gallery] .slides > img {
width: 100%;
height: 100%;
object-fit: cover;
transition: 0.4s;
}
<div data-gallery="one" class="gallery">
<div class="slides"></div>
<button class="prev" type="button">PREV</button>
<button class="next" type="button">NEXT</button>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
P.S: As a side-note, the following
$( '#left' ).css('width', '900px');
$( '#left' ).css('height', '400px');
$( '#left' ).css('overflow', 'hidden');
is a bit verbose. Instead pass an object literal {} like:
$( '#left' ).css({width:900, height:400, overflow:"hidden"});

Related

Loop using jquery and javascript

I'm having some trouble thinking of how to do this properly.
Right now, I have some jquery that looks like this:
$( "#person_0" ).click(function() {
$( "[id^=person_]" ).removeClass("active");
$( "#person_0" ).addClass("active");
$( "[id^=bio_]" ).hide();
$( "#bio_0" ).show();
$( "[id^=hoverInfo_]" ).hide();
$( "#hoverInfo_0" ).show();
});
$( "#person_1" ).click(function() {
$( "[id^=person_]" ).removeClass("active");
$( "#person_1" ).addClass("active");
$( "[id^=bio_]" ).hide();
$( "#bio_1" ).show();
$( "[id^=hoverInfo_]" ).hide();
$( "#hoverInfo_1" ).show();
});
...
...
Essentially, if you click a person_0 div id, a class of active is added to that and both hoverInfo_0 and bio_0 show up. At the same time, all other ids go and hide (for example, hoverInfo_1, hoverInfo_2, bio_1, bio_2, etc.
This is super inefficient because I want there to be 100+ person_ ids. I feel like I'm overlooking something obvious.
Pseudo code right now:
if person_0 div is clicked
give person_0 div active class
show hoverInfo_0
show bio_0
hide all other hoverInfo_# (say 1-1000)
hide all other bio_# (say 1-1000)
else if person_1 div is clicked
give person_1 div active class
show hoverInfo_1
show bio_1
hide all hoverInfo_# (say 1-1000) that does not equal hoverInfo_1
hide all bio_# (say 1-1000) that does not equal bio_1
else if ...
else if ...
I'm having a hard time trying to figure out how I can loop this around or use a variable in place of the _# value to make this more efficient. Any thoughts?
how I can loop this around or use a variable in place of the _# value
to make this more efficient. Any thoughts?
Try this approach using starts with and filter
$( "[id^='person_']" ).click(function() {
var id = $( this )[0].id;
console.log(id);
var counter = id.split("_").pop();
$( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
$( "[id^='bio_']" ).hide().filter( "#bio_" + counter ).show();
$( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});
Demo
$( "[id^='person_']" ).click(function() {
var id = $( this )[0].id;
console.log(id);
var counter = id.split("_").pop();
$( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
$( "[id^='bio_']" ).hide().filter( "#bio_" + counter ).show();
$( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});
.bio, .hoberInfo
{
display: none;
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="person_1">Person 1</div>
<div id="bio_1" class="bio">Bio 1</div>
<div id="hoverInfo_1" class="hoberInfo">HoverInfo 1</div>
<div id="person_2">Person 2</div>
<div id="bio_2" class="bio">Bio 2</div>
<div id="hoverInfo_2" class="hoberInfo">HoverInfo 2</div>
<div id="person_3">Person 3</div>
<div id="bio_3" class="bio">Bio 3</div>
<div id="hoverInfo_3" class="hoberInfo">HoverInfo 3</div>

Put transition to hover in jquery

I have this script in jquery which makes a hover image (in the hover replaces the images) .
The specific question is how do I place a transition ?
$( "figure.salud img" ).hover(
function() {
$( this ).attr("src","img/salud5.jpg");
},function() {
$( this ).attr("src","img/salud5-gris.jpg");
}
);
Are you looking for something as this ,do let me know if something else was expected!
$( ".salud img" ).hover(
function() {
$( this ).fadeOut(0).attr("src","https://pmcdeadline2.files.wordpress.com/2014/06/yahoo-logo.jpg").fadeIn(500);
},function() {
$( this ).fadeOut(0).attr("src","http://velocityagency.com/wp-content/uploads/2013/08/go.jpg").fadeIn(500);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="salud">
<img src="http://velocityagency.com/wp-content/uploads/2013/08/go.jpg" width="160" height="160"/>
</div>
JS FIDDLE: https://jsfiddle.net/nhwuh7pb/9/

drag and drop issue jquery

I have the code below using the script i am making stuff draggable and droppable. currently i have two pieces for draggable content, and two place they can be dropped if correct then the system will change and say correct, I would like to know if there is away that i would be able just create the HTML divs and the code runs through and matches the draggable to the dropable. I have people that have a non-technical backdround, have basic HTML knowledge so thy now how to add divs and remove them but they are able to deal with script, i would like to know, if i had ID of 1-10 for the draggable content and the same for the dropable 1-10 so id 1 draggable can only be added to id one droppable.
<meta charset="utf-8">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="hhtps:/resources/demos/style.css">
<style>
#droppable,#droppable2 { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
#draggable, #draggable2 { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
</style>
<script>
$(function() {
$( "#draggable, #draggable2" ).draggable();
$( "#droppable" ).droppable({
accept: "#draggable",
drop: function( event, ui ) {
$( this )
.removeClass("ui-widget-header")
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
},
out: function( event, ui ) {
$( this ).removeClass( "ui-state-highlight" ).addClass( "ui-widget-header" )
.find( "p" )
.html( "accept" );
}
});
$( "#droppable2" ).droppable({
accept: "#draggable2",
drop: function( event, ui ) {
$( this )
.removeClass("ui-widget-header")
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
},
out: function( event, ui ) {
$( this ).removeClass( "ui-state-highlight" ).addClass( "ui-widget-header" )
.find( "p" )
.html( "accept" );
}
});
});
</script>
<div id="draggable2" class="ui-widget-content">
<p>I'm draggable but can't be dropped</p>
</div>
<div id="draggable" class="ui-widget-content">
<p>Drag me to my target</p>
</div>
<div id="droppable" class="ui-widget-header">
<p>accept: '#draggable'</p>
</div>
<div id="droppable2" class="ui-widget-header">
<p>accept: '#draggable2'</p>
</div>
You will need to avoid using HTML id for this and start using classes. Here is how to do that, with a working example:
Your HTML:
<div id="draggable_2" class="ui-widget-content draggable-item">
<p>draggable_2</p>
</div>
<div id="draggable" class="ui-widget-content draggable-item">
<p>draggable</p>
</div>
<div class="ui-widget-header droppable-item" data-accept="#draggable">
<p></p>
</div>
<div class="ui-widget-header droppable-item" data-accept="#draggable_2">
<p></p>
</div>
<div class="ui-widget-header droppable-item" data-accept="#draggable_3">
<p></p>
</div>
Your javascript:
$(function () {
$(".draggable-item").draggable();
$('.droppable-item').each(function (i, ele) {
// Gets the accepted from the HTML property "data-accept"
var accept = $(this).data('accept');
// This is just to show what the item accepts. you can remove it.
$(this).find('p').text('accepts: ' + accept);
// Init the jQuery UI droppable()
$(this).droppable({
accept: accept,
drop: function (event, ui) {
$(this)
.removeClass("ui-widget-header")
.addClass("ui-state-highlight")
.find("p")
.html("Dropped!");
},
out: function (event, ui) {
$(this).removeClass("ui-state-highlight").addClass("ui-widget-header")
.find("p")
.html("accept: " + accept);
}
});
});
});
If I understand your question correctly, you want every draggable to be droppable only its droppable and no other droppable div.
You've already achieved this by adding the accept: "#draggable" in your code for every droppable.
You can add this extra line of code so that if your draggable is dropped anywhere other than its droppable, it will go back to its droppable.
$( "#draggable, #draggable2" ).draggable({ revert: "invalid" });
This code can be shortened if you added the same class (like class=draggables to every draggable html element and then you can juse use
$( ".draggables" ).draggable({ revert: "invalid" }); to mark them all.
Here is a jsfiddle to show the example.

JQuery - Adding class onto element, and then interacting with that class doesn't work

When you click ( ".toggle-button a" ), it adds .close class to itself. And fades in .info-overlay
This works fine, but when you click it again, I want info-overlay to fade out again, and the close class to be removed. But this doesn't work.
Am I missing something here?
http://jsfiddle.net/bazzle/xpS9P/1/
html
<div class="toggle-button">
<a>click</a>
</div>
<div class="info-overlay">
content
</div>
css
.info-overlay{
display:block;
width:100px;
height:100px;
background-color:green;
display:none;
};
js
$( ".toggle-button a" ).click(function() {
$( ".info-overlay" ).fadeIn("500");
$(this).addClass('close');
});
$( ".toggle-button a.close" ).click(function(){
$( ".info-overlay").fadeOut("500");
$(this).removeClass('close');
});
Use event delegation:
Change
$( ".toggle-button a.close" ).click(function(){
$( ".info-overlay").fadeOut("500");
$(this).removeClass('close');
});
to:
$(document).on('click',".toggle-button a.close",function(){
$( ".info-overlay").fadeOut("500");
$(this).removeClass('close');
});
Because a .click() is attach and forget handler, but .on() is dynamic.
see updated Fiddle
$( ".toggle-button a" ).click(function() {
if($(this).hasClass('close')){
$( ".info-overlay").fadeOut("500");
$(this).removeClass('close');
}else{
$( ".info-overlay" ).fadeIn("500");
$(this).addClass('close');
}
});
reference hasClass()
You could use delegation or just set your logic as following:
DEMO
$(".toggle-button a").click(function () {
$(".info-overlay").fadeToggle(500).toggleClass('close');
});

Why does my jquery function not work on div in page loaded by ajax

I'm just starting out with jquery. Already learned some things and like it, but I have been struggling with the following issue for a few days.
I copied the "dialog-confirm"-function from https://jqueryui.com/. I placed this script between the tags on my index.php page.
<script type = "text/javascript">
$(document).ready(function(){
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
$(window).resize(function() {
$('#scrollpage').height($(window).height() - 250);
});
$(window).trigger('resize');
$('.container').on('click', '.mainmenu', function(event){
event.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data) {
//alert(data);
$("#div1").load(url);
});
$( this ).parent().addClass('current_page_item');
$( this ).parent().siblings().removeClass('current_page_item');
});
$('.container').on('click', '.rapport', function(event){
event.preventDefault();
//$(".dialog-confirm").dialog( "open" );
var url = $(this).attr('href');
$.get(url, function(data) {
//alert(data);
$("#div1").load(url);
});
});
});
</script>
If i place the matching div in the same index.php page. It works fine, the div pops up.
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Blablabla</p>
</div>
However when i place the div in a page which is loaded by ajax in the div1, then I cant get it to work.
<div class="scrollpage" id="scrollpage">
<div class="container" class="page" id="div1">
</div>
</div>
Can anyone explain to me why this is, and how I can fix this?
What's happening is that your $(document).ready() function executes as soon as the DOM is loaded. This DOM contains just what it is in the html file. At that time, there's no div with an id equal to 'dialog-confirm'. Loading pieces of HTML with ajax doesn't trigger a DOMReady event. What you've got to do is to call the .dialog() jQuery function AFTER you've loaded the div with Ajax:
$("#div1").load(url, function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
Here is what happens in your program(loading div with ajax):
First, your script initiates dialog window container by looking an element with id dialog-confirm.
Since, you don't have an element with that id yet, dialog container cannot be prepared.
There are two ways you can make it work:
Call dialog() after ajax requests,
Place div statically on page and change content with ajax request.
Solutions:
1- Use the code below instead of $("#div1").load(url);
$("#div1").load(url, function(){
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
2- Place divs statically on your page:
<div class="scrollpage" id="scrollpage">
<div class="container" class="page" id="div1">
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Blablabla</p>
</div>
</div>
</div>
Then load just <p>... with $("#dialog-confirm").load(data); instead of $("#div1").load(url);.
Your jquery is executed only once after your page is loaded. Then is initiating everything needed for the tool!
This means every .container is being 'transformed'.
If you later add a new div.container it is not 'transformed' yet. You have to execute the jquery again after your div is appended!

Categories