How to switch images using JS? - javascript

I have a simple code that switches text when an image is clicked:
js:
$(document).ready(function() {
$('.srb').on('click', function() {
var r = $('.localization').each(function() {
var el = $(this);
var key = (el.attr('caption'));
el.text(srb[key]);
});
});
$('.eng').on('click', function() {
var r = $('.localization').each(function() {
var el = $(this);
var key = (el.attr('caption'));
el.text(eng[key]);
});
});
var srb = {
welcome: 'Добро дошли на наш сајт!'
};
var eng = {
welcome: 'Welcome to our site!'
};
});
HTML:
<span class='localization' caption='welcome'>Welcome to our site!</span>
<img src="img/Serbia.png" value='srb' class="srb" id="flag"/>
<img src="img/United-Kingdom.png" class='eng' value='eng'/>
Is it possible to switch images when language is switched (for example, when English language is set, GB flag disappears)?

Edit html like that
<img src="img/Serbia.png" value='srb' class="image_flag srb" id="flag"/>
<img src="img/United-Kingdom.png" class="image_flag eng" value="eng"/>
add class hidden element
.d-none{
display: none !important;
}
<script>
function activeImageFlag(flagActive){
document.querySelectorAll(".image_flag").forEach(function(flagImage){
flagImage.classList.add('d-none')
});
document.querySelector(".image_flag." + flagActive).classList.remove('d-none')
}
</script>

Related

How to toggle a form through button?

I would like to show a form through button click in JS vanilla but nothing work. Here is my code
/* ======= Model ======= */
var model = {
currentCat: null,
cats: [
{
clickCount : 0,
name : 'Tabby',
imgSrc : 'img/434164568_fea0ad4013_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/bigtallguy/434164568'
},
{
clickCount : 0,
name : 'Tiger',
imgSrc : 'img/4154543904_6e2428c421_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/xshamx/4154543904'
},
{
clickCount : 0,
name : 'Scaredy',
imgSrc : 'img/22252709_010df3379e_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/kpjas/22252709'
},
{
clickCount : 0,
name : 'Shadow',
imgSrc : 'img/1413379559_412a540d29_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/malfet/1413379559'
},
{
clickCount : 0,
name : 'Sleepy',
imgSrc : 'img/9648464288_2516b35537_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
}
]
};
/* ======= Octopus ======= */
var octopus = {
init: function() {
// set our current cat to the first one in the list
model.currentCat = model.cats[0];
// tell our views to initialize
catListView.init();
catView.init();
adminView.init();
},
getCurrentCat: function() {
return model.currentCat;
},
getCats: function() {
return model.cats;
},
// set the currently-selected cat to the object passed in
setCurrentCat: function(cat) {
model.currentCat = cat;
},
// increments the counter for the currently-selected cat
incrementCounter: function() {
model.currentCat.clickCount++;
catView.render();
}
};
/* ======= View ======= */
var catView = {
init: function() {
// store pointers to our DOM elements for easy access later
this.catElem = document.getElementById('cat');
this.catNameElem = document.getElementById('cat-name');
this.catImageElem = document.getElementById('cat-img');
this.countElem = document.getElementById('cat-count');
// on click, increment the current cat's counter
this.catImageElem.addEventListener('click', function(){
octopus.incrementCounter();
});
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
// update the DOM elements with values from the current cat
var currentCat = octopus.getCurrentCat();
this.countElem.textContent = currentCat.clickCount;
this.catNameElem.textContent = currentCat.name;
this.catImageElem.src = currentCat.imgSrc;
}
};
var catListView = {
init: function() {
// store the DOM element for easy access later
this.catListElem = document.getElementById('cat-list');
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
var cat, elem, i;
// get the cats we'll be rendering from the octopus
var cats = octopus.getCats();
// empty the cat list
this.catListElem.innerHTML = '';
// loop over the cats
for (i = 0; i < cats.length; i++) {
// this is the cat we're currently looping over
cat = cats[i];
// make a new cat list item and set its text
elem = document.createElement('li');
elem.textContent = cat.name;
// on click, setCurrentCat and render the catView
// (this uses our closure-in-a-loop trick to connect the value
// of the cat variable to the click event function)
elem.addEventListener('click', (function(catCopy) {
return function() {
octopus.setCurrentCat(catCopy);
catView.render();
};
})(cat));
// finally, add the element to the list
this.catListElem.appendChild(elem);
}
}
};
var adminView = {
init: function() {
this.formElement = document.getElementById('admin-form');
this.buttonAdmin = document.getElementById('admin-button');
console.log(this);
this.render();
},
render: function() {
this.formElement.style.display = 'none';
console.log(this);
this.buttonAdmin.addEventListener('click', (function(form){
return form.style.display = 'block';
})(this.formElement));
console.log(this);
}
};
// make it go!
octopus.init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
</head>
<body>
<ul id="cat-list"></ul>
<div id="cat">
<h2 id="cat-name"></h2>
<div id="cat-count"></div>
<img id="cat-img" src="" alt="cute cat">
</div>
<div>
<button type="button" id="admin-button">Admin</button>
</div>
<div id="admin-form">
<p>Name</p>
<input type="text" name="new-cat-name" value="">
<p>Img URL</p>
<input type="text" name="new-img-url" value="">
<p># Count</p>
<input type="text" name="new-count-number" value="">
<br>
<button type="button" name="save">Save</button>
<button type="button" name="cancel">Cancel</button>
</div>
<script src="js/app.js"></script>
<script>
if(!document.getElementById('admin-button').active){
document.getElementById('admin-form').style.display ='none';
}
</script>
</body>
</html>
I don't understand why the form (#admin-form) is shown when the page is loaded, it should be shown only when the button (#admin-button) is clicked.
Update: I added the script to hide the form in HTML file.
Here's your problem:
this.buttonAdmin.addEventListener('click', (function(form){
return form.style.display = 'block';
})(this.formElement));
You wrap the handler function in parens and call it immediately. Try:
this.buttonAdmin.addEventListener('click', function(){
this.formElement.style.display = 'block';
}.bind(this));
Or, if you don't want to use bind for whatever reason:
var form = this.formElement;
this.buttonAdmin.addEventListener('click', function(){
form.style.display = 'block';
});

Finding nearest image element and refresh image source

I have the following markup
<div class="col-md-4">
<div class="row">
<img name="previewImage" alt="" src="" style="max-height:300px;max-width :350px;">
</div>
<div class="row">
<button name="btnPushPhoto" type="button" class="btn btn-default" tabindex="-1">Push</button>
<button name="btnRemovePhoto" type="button" class="btn btn-default" tabindex="-1">Remove</button>
</div>
</div>
When I click on the remove photo button, I'm able to set my image to null (in the server side), however at the client side, I'm having some difficulties locating the image tag, and refresh it.
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
var img = $(this).parent().parent().find('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Nothing seems to happen here. No error in the browser's console.
This is the output of console.log(img);
[prevObject: x.fn.x.init[0], context: undefined, selector: "[name=previewImage]"]
You should store the $(this) in some variable before post request since inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to :
_this = $(this);
Then you could use parents() instead :
var img = _this.parents('.col-md-4').find('[name="previewImage"]');
Hope this helps.
Try this:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
var $this = $(this); //Insert this line
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = $this.closest("div.col-md-4").find("img"); //USE $this
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
You should move img definition before the $.post function:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var img = $(this).parent().parent().find('[name=previewImage]');
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
I think the way you are searching/looking at the relationship needs to be edited slightly. There are a few jquery methods that may help but I usually like to map out the relationships in my head like below:
<div name="PARENT_of_PARENT_of_X">
<div name="Sibling_of_PARENT_of_X OR child_of_PARENT_of_PARENT_of_X>
<img name="Child_of_SIBLING_of_PARENT_of_X OR CHILD_of_PARENT_of_PARENT_of_X" />
</div>
<div name="PARENT_of_X">
<button ></button>
<button name="SOURCE X" >Remove</button>
</div>
</div>
You could use jQuery selector "closest"
https://api.jquery.com/closest/
$(document).on("click", "[name=btnRemovePhoto]", function () {
var clickedButton = $(this);
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = clickedButton .closest("div.col-md-4").find("img");
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});

Get the data attribute of a div that WASN'T clicked

I have two divs.
<div class="my_thing" data-id="123"></div>
<div class="my_thing" data-id="529"></div>
When a div is clicked, I want to get the data-id for the clicked div, and the data-id for the one that wasn't clicked. So I end up with this object:
{
clicked_id = 123,
not_clicked_id = 529
}
How can I do this? This is what I have so far.
$('.my_thing').click(function(){
var clicked_id = $(this).attr('data-id');
var not_clicked_id = ?????
});
If there will be only 2 .my_thing elements then you can use .not() like
var $divs = $('.my_thing').click(function() {
var clicked_id = $(this).attr('data-id');
var not_clicked_id = $divs.not(this).attr('data-id');
log(clicked_id + '-' + not_clicked_id)
});
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).prependTo($log)
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my_thing" data-id="123">123</div>
<div class="my_thing" data-id="529">529</div>
<div id="log"></div>

Firebase events not triggered properly when joining tables with Firebase-util

I'm using Firebase-util's intersection function to find all the comments for a given link. This seems to work fine the first time I call the join, but it doesn't seem to properly notify my value callback when I remove the contents of the database and replace them again. Shouldn't the references keep working as long as the resource path remains the same?
Run this example. When you click the button, it erases and recreates the data. As you can see, the comment list is not repopulated after the data gets recreated.
<link rel="import" href="https://www.polymer-project.org/components/polymer/polymer.html">
<script src="http://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebase-util/0.1.0/firebase-util.min.js"></script>
<polymer-element name="my-element">
<template>
<h1>Test of Firebase-util.intersection</h1>
<div>
<button on-click={{initializeFirebase}}>Reset data</button>
</div>
<ul>
<template repeat="{{rootComment in comments}}">
<li>{{rootComment.comment.content}}
<ul>
<template repeat="{{subComment in rootComment.children}}">
<li>{{subComment.comment.content}}
<ul>
<template repeat="{{subSubComment in subComment.children}}">
<li>{{subSubComment.comment.content}}</li>
</template>
</ul>
</li>
</template>
</ul>
</li>
</template>
</ul>
</template>
<script>
Polymer('my-element', {
ready: function() {
var sanitizeUrl = function(url) {
return encodeURIComponent(url).replace(/\./g, '%ZZ');
};
var baseUrl = "https://nested-comments-test.firebaseio.com";
var linkUrl = baseUrl +
'/links/' +
sanitizeUrl(document.URL) +
'/comments';
var commentsUrl = baseUrl + '/comments';
var root = new Firebase(baseUrl);
this.initializeFirebase = function() {
function addLink(url, callback) {
var key = sanitizeUrl(url),
newLink = {
url: url,
createdAt: Firebase.ServerValue.TIMESTAMP
};
root.child('/links/' + key).update(newLink);
callback(key);
}
function addComment(attributes, callback) {
return root.child('/comments').push(attributes, callback);
}
function onCommentAdded(childSnapshot) {
var newCommentId = childSnapshot.name(),
attributes = {},
link = childSnapshot.val().link,
url = '/links/' + link + '/comments';
attributes[newCommentId] = true;
root.child(url).update(attributes);
}
root.remove(function() {
root.child('/comments').on('child_added', onCommentAdded);
addLink(document.URL, function(link) {
var attributes = {
link: link,
content: "This is the first comment."
},
firstCommentId, secondCommentId;
firstCommentId = addComment(attributes).name();
attributes = {
link: link,
content: "This is a reply to the first.",
replyToCommentId: firstCommentId
};
secondCommentId = addComment(attributes).name();
attributes = {
link: link,
content: "This is a reply to the second.",
replyToCommentId: secondCommentId
};
addComment(attributes);
attributes = {
link: link,
content: "This is another reply to the first.",
replyToCommentId: firstCommentId
};
addComment(attributes);
});
});
};
this.initializeFirebase();
var findChildrenForComment = function(snapshot, parentCommentId) {
var returnVal = [];
snapshot.forEach(function(snap) {
var comment = snap.val(),
commentId = snap.name();
if (comment.replyToCommentId === parentCommentId) {
var children = findChildrenForComment(snapshot, commentId);
var obj = {
commentId: commentId,
comment: comment,
parentId: parentCommentId
};
if (children.length) {
obj.children = children;
}
returnVal.push(obj);
}
});
return returnVal;
};
this.ref = Firebase.util.intersection(
new Firebase(linkUrl),
new Firebase(commentsUrl)
);
this.comments = {};
var that = this;
this.ref.on('value', function(snapshot) {
that.comments = findChildrenForComment(snapshot);
});
}
});
</script>
</polymer-element>
<my-element></my-element>
Apparently deleting a path entirely causes all callbacks on it to be canceled. The workaround for this behavior is to remove children one at a time rather than deleting their parent path.

jquery trouble - onclick for gallery

I am trying to use image gallery for my website that I found here. I want to add one more functionality to this gallery.. I want a large image to be linked and when clicked on it to open in new tab url that is defined in code.
I have included the full code here:
<script type="text/javascript">
$(document).ready(function()
{
/*Your ShineTime Welcome Image*/
var default_image = 'images/large/default.jpg';
var default_caption = 'Welcome to my portfolio';
/*Load The Default Image*/
loadPhoto(default_image, default_caption);
function loadPhoto($url, $caption)
{
/*Image pre-loader*/
showPreloader();
var img = new Image();
jQuery(img).load( function()
{
jQuery(img).hide();
hidePreloader();
}).attr({ "src": $url });
$('#largephoto').css('background-image','url("' + $url + '")');
$('#largephoto').data('caption', $caption);
}
/* When a thumbnail is clicked*/
$('.thumb_container').click(function()
{
var handler = $(this).find('.large_image');
var newsrc = handler.attr('src');
var newcaption = handler.attr('rel');
loadPhoto(newsrc, newcaption);
});
/*When the main photo is hovered over*/
$('#largephoto').hover(function()
{
var currentCaption = ($(this).data('caption'));
var largeCaption = $(this).find('#largecaption');
largeCaption.stop();
largeCaption.css('opacity','0.9');
largeCaption.find('.captionContent').html(currentCaption);
largeCaption.fadeIn()
largeCaption.find('.captionShine').stop();
largeCaption.find('.captionShine').css("background-position","-550px 0");
largeCaption.find('.captionShine').animate({backgroundPosition: '550px 0'},700);
Cufon.replace('.captionContent');
},
function()
{
var largeCaption = $(this).find('#largecaption');
largeCaption.find('.captionContent').html('');
largeCaption.fadeOut();
});
/* When a thumbnail is hovered over*/
$('.thumb_container').hover(function()
{
$(this).find(".large_thumb").stop().animate({marginLeft:-7, marginTop:-7},200);
$(this).find(".large_thumb_shine").stop();
$(this).find(".large_thumb_shine").css("background-position","-99px 0");
$(this).find(".large_thumb_shine").animate({backgroundPosition: '99px 0'},700);
}, function()
{
$(this).find(".large_thumb").stop().animate({marginLeft:0, marginTop:0},200);
});
function showPreloader()
{
$('#loader').css('background-image','url("images/interface/loader.gif")');
}
function hidePreloader()
{
$('#loader').css('background-image','url("")');
}
});
</script>
And I have 15 thumbnails/photos like this:
<div class="thumbnails">
<br><br><br>
<!-- start entry-->
<div class="thumbnailimage">
<div class="thumb_container">
<div class="large_thumb">
<img src="images/thumbnails/sample1.jpg" class="large_thumb_image" alt="thumb">
<img alt="" src="images/large/sample1.jpg" class="large_image" rel="Image Sample">
<div class="large_thumb_border"> </div>
<div class="large_thumb_shine"> </div>
</div>
</div>
</div>
<!-- end entry-->
</div>
Any help? Thanks.
This should work, all you have to do is add data-large attributes to each image and on hover it displays a tooltip with the large image inside.
http://jsfiddle.net/DSjLk/

Categories

Resources