How to get product name and image dynamically using jQuery? - javascript

Actually I am doing add to cart functionality using jQuery. On click of add to cart button product name and image should come. Statically I can do but how to get the product name and image dynamically for all divs is what I want. Please somebody help with this.
This is my HTML markup:
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/barcunda-black.jpg" class="lazy-loaded"/>
<h4>Barcunda Black</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/bruno-white.jpg" class="lazy-loaded"/>
<h4>Bruno White</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/fantasy-brown.jpg" class="lazy-loaded"/>
<h4>Fantasy Brown</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/iceberg.jpg" class="lazy-loaded"/>
<h4>Iceberg</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/mercury-white.jpg" class="lazy-loaded"/>
<h4>Mercury White</h4>
</div>
</div>
And here my jQuery code:
$(document).ready(function(){
//alert("coming");
var cart = [];
$(function () {
if (localStorage.cart) {
cart = JSON.parse(localStorage.cart);
// console.log(cart);
showCart();
}
});
});
function addToCart() {
how to get product name and image here for all divs?
// alert(price);alert(name);alert(qty);return false;
// update qty if product is already present
for (var i in cart) {
if(cart[i].Product == name) {
cart[i].Qty = qty;
showCart();
saveCart();
return;
}
}
// create JavaScript Object
var item = { Product: name, Price: price, Qty: qty };
//console.log(item);return false;
// alert(item);return false;
cart.push(item);
console.log(cart);return false;
saveCart();
showCart();
}
function deleteItem(index){
//alert(index);return false;
cart.splice(index,1); // delete item at index
showCart();
saveCart();
}
function saveCart() {
if ( window.localStorage) {
localStorage.cart = JSON.stringify(cart);
}
}

Add this to your addToCart() function on the first line:
var $parent = $(this).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
UPDATE
function addToCart(elem){
var $parent = $(elem).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
// then the rest of your existing code
}

I see a very little jQuery involved in your addToCart function. You could simply refer it's parent container to get the source attribute of the image and the product title text:
First of all, change the way button is clicked, instead of using inline function, you could add a class reference on it, and fire the addToCart button as callback:
...
$('.btn-add').on('click', addToCart);
function addToCart() {
var container = $(this).parents('.prdtitem');
var thumbnailImage = container.find('img.lazy-loaded').attr('src');
var productTitle = container.find('h4').text();
// ... rest of your code
}
Now you got the image source within the thumbnailImage variable and the title in the productTitle.

Create a click event:
$('.cartBg a').click(function(){
var img = $(this).closet('.cartBg').find('img').attr('src');
var title = $(this).closet('.cartBg').find('h4').text();
addToCart();
alert(title);
});

You can use your function like this -
JAVASCRIPT
function addToCart(obj){
var product_name = $(obj).closest('.prdtitem').find('h4').text();
var image_src = $(obj).closest('.prdtitem').find('img.lazy-loaded').attr('src');
alert(product_name,image_src);
}
In element you use this function call like this onclick=addToCart(this).

Related

addEventListener for click is not working

const renderNote = data => {
const postListRef = ref(db, 'Notes/' +data.key);
console.log(data.key)
const newPostRef = push(postListRef);
var status = 'Pending'
var title = 'new note'
var date = '29-4-2022'
var note = 'newly added note'
let card =
`<div id="single-card" class="col-lg-4 col-md-3" data-id=${data.key} ><!--outer layer of single card-->
<div class="card card-body"><!--card body-->
<p class="badge" id="status" style="background-color: rgb(0, 81, 81);">${status}</p>
<span class="side-stick"></span> <!--side-stick color-->
<!-- note title -->
<h5 class="note-title text-truncate w-75 mb-0" >${title}<i class="point fa fa-circle ml-1 font-10"></i></h5><!--fa fa-circle is for the dot dot dot(continuity)-->
<p class="note-date font-12 text-muted mt-0">${date}</p>
<!--note description-->
<div class="note-content">
<p class="note-inner-content text-muted" >${note}<i class="point fa fa-circle ml-1 font-10"></i></p>
</div>
<button class="btn btn-del">Delete${data.key}</button>
<div id="actions" >
</div>
</div>
</div>`
prod.innerHTML += card;
const btnDelete = document.querySelector(`[data-id='${data.key}'] .btn-del`);
console.log(btnDelete);
btnDelete.addEventListener("click",()=>{
console.log('deleting');
});
}
EventListener is not working. But when I print the btnDelete(console.log(btnDelete);) it is printing correctly. But the eventlistener is not workingDoes anybody know what is wrong with the code?
Why donĀ“t you use onclick in HTML?
<button onclick="console.log('deleting');" class="btn btn-del">Delete${data.key}</button>
You can even call a delete Function like that:
HTML:
<button onclick="deleteCard(${data.key})" class="btn btn-del">Delete${data.key}</button>
JavaScript:
function deleteCard(key) {
console.log(`Delete Card with key: ${key}`)
}

data- attribute not working to grab dynamic id from foreach

I am using JS in a razor page to grab a dynamic ID from a col in a foreach.
In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.
Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.
View:
<div class="list-group container" id="JobRequestMonitorTable">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="margin-bottom:0px;">
<div class="col-md-4"> Job Code </div>
<div class="col-md-4"> Description </div>
<div class="col-md-2"> Schedule </div>
<div class="col-md-1"> Running </div>
<div class="col-md-1"></div>
</div>
#if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
{
<div class="row list-group-item-danger">
<div class="col-md-1 text-center">#ViewBag.ErrorMessage</div>
</div>
}
#foreach (var item in Model.JobRequests)
{
<div class="row list-group-item container">
<div class="hidden" data-id="#item.JobRequestId" id="requestId">#item.JobRequestId</div>
<div class="col-md-4">#item.JobCode</div>
<div class="col-md-4">#item.Description</div>
<div class="col-md-2">#item.Schedule</div>
#if (#item.IsRunning == true)
{
<div class="col-md-1" style="margin-left:25px;"><span class="glyphicon glyphicon-ok"></span></div>
<div class="col-md-1"></div>
}
else
{
<div class="col-md-1"></div>
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>
</div>
}
</div>
}
</div>
JS:
$("button").click(function () {
var col = $('#requestId');
var jobRequestId = col.data('Id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
Really the only important part to see in the JS is var col = $('#requestId');
var jobRequestId = col.data('Id');
But I suppose I will include the whole script just in case people ask.
Your loop is creating multiple #requestId and #paramModalBtn elements when id attributes have to be unique within the DOM. Change the logic to use common classes instead. Then you can traverse the DOM to find the elements related to the button which was clicked. Try this:
$("button").click(function() {
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
console.log(jobRequestId);
// AJAX request...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<div class="row list-group-item container">
<div class="hidden requestId" data-id="foo-bar">Job #1</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
<div class="row list-group-item container">
<div class="hidden requestId" data-id="lorem-ipsum">#Job #2</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
All of your items inside the loop are getting the same id attribute, it is hard-codded
id="requestId"
the jQuery selector $('#requestId') is getting back the first one, this is by design.
I would add a data-id to each button and select the relevant col with that id.
For example the button will get:
<button data-col-id="#item.JobRequestId" class="glyphicon glyphicon-list-alt btn btn-primary"></button>
And then, its easy to grab that info on click:
$("button").click(function () {
var jobRequestId = $(this).data('col-id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
I like this solution as you are not depended on your HTML structure and hierarchy thus selectors won't break often.
Once you have a button for each item, you could also store the data into the button value attribute, which leads to a simple implementation in the JS:
$("button").click(function (e) {
var jobRequestId = $(e.target).val();
console.log(jobRequestId);
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="1">Job 1</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="2">Job 2</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="3">Job 3</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="4">Job 4</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="5">Job 5</button>
Obs.: value must be equal to #item.JobRequestId like so: <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="#item.JobRequestId">Job 5</button>

MVC javascript display selected data

First of all, I list the e-mail from coming ActionResult in the first cycle.
I want to see the details by clicking on the listed data. I open with the help of jQuery details. The problem arises in this section. in this case ,the opening of the details of the first mail in the detail of each row.
There are details of the message in the second loop.To connect to the two loops in a guid font was coming. (MessageId).
id=messageId (guid type)
mailing list
<div class="message-list-container">
<div class="message-list" id="message-list">
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
<span class="sender" title="#item.From">
#item.From
</span>
<span class="time">#mvcHelper.saatAyarla(item.Date)</span>
#if(item.Attachments.Any())
{
<span class="attachment">
<i class="ace-icon fa fa-paperclip"></i>
</span>
}
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
</div>
}
</div>
</div>
mailing details
<!--Messsage details-->
#foreach (var item in Model)
{
<!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
<div class="message-header clearfix">
<div class="pull-left">
<span class="blue bigger-125"> #item.Subject </span>
<div class="space-4"></div>
<i class="ace-icon fa fa-star orange2"></i>
<img class="middle" alt="John's Avatar" src="/Areas/admin/Content/images/avatars/avatar.png" width="32" />
#item.From
<i class="ace-icon fa fa-clock-o bigger-110 orange middle"></i>
<span class="time grey">#mvcHelper.saatGoster(item.Date)</span>
</div>
</div>
<div class="hr hr-double"></div>
<div class="message-body">
<p>
#item.TextBody
</p>
</div>
<div class="hr hr-double"></div>
<!--Eklenti paneli-->
<div class="message-attachment clearfix">
#if (item.Attachments.Any())
{
<div class="attachment-title">
<span class="blue bolder bigger-110">Eklentiler</span>
<span class="grey">(#item.Attachments.Count() Dosya)</span>
</div>
<ul class="attachment-list pull-left list-unstyled">
#foreach (var attachment in item.Attachments)
{
<li>
<a href="#" class="attached-file">
<i class="ace-icon fa fa-file-o bigger-110"></i>
<span class="attached-name">#mvcHelper.getAttachmentName(attachment.ToString())</span>
</a>
<span class="action-buttons">
<a href="#">
<i class="ace-icon fa fa-download bigger-125 blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o bigger-125 red"></i>
</a>
</span>
</li>
}
</ul>
}
</div>
</div><!-- /.message-content -->
}
<!--Eklenti paneli Son-->
<!--message details end-->
loop connecting two points.
first foreach = <div id="#item.MessageId" class="message-item">
//Places where the problem is. They need to be connected.
second foreach = <!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
var content = message.find('.message-content:last').html($('#id-message-content').html());
jQuery code
$('.message-list .message-item .text').on('click', function () {
var message = $(this).closest('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').remove();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message
.addClass('message-inline-open')
.append('<div class="message-content" />');
var content = message.find('.message-content:last').html($('#id-message-content').html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Your first problem is that you are creating multiple elements with identical id properties. This makes your HTML invalid.
Here is the problem code:
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
...
#foreach (var item in Model)
{
<div class="hide message-content" id="#item.MessageId">
...
For each message in your model, this will create 2 <div> elements whose id has the value of the #item.MessageID variable. The second of these is and illegal element because it has the same ID as an earlier element. You will need to make these <div>s have unique IDs.
The second problem is:
When you run
var content = message.find('.message-content:last').html($('#id-message-content').html());
this part:
$('#id-message-content').html()
cannot find anything because there is no element whose id is "id-message-content". Also every time you open the message, you are appending another "message-content" div into the message-item. This is not necessary.
To fix these issues, you can change the code like this:
First loop:
#foreach (var item in Model)
{
<div data-messageid="#item.MessageId" class="message-item">
...
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
<div class="message-content" hidden></div>
...
Second loop:
#foreach (var item in Model)
{
<div class="hide message-content" id="message-content-#item.MessageId">
...
jQuery:
$('.message-list .message-item .text').on('click', function () {
var message = $(this).parents('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').hide();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message.addClass('message-inline-open');
var content = message.find(".message-content");
content.show();
content.html($('#message-content-' + message.data("messageid")).html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Solved
public static class mvcHelper
{
public static string variableReplace(string id)
{
string yazi = null;
if (id != null)
{
yazi = id.Replace('#', 'a').ToString();
}
else
{
yazi = id;
}
return yazi;
}
}
<div data-messageid="#mvcHelper.variableReplace(item.MessageId)" class="message-item">
<div class="hide message-content" id="message-content-#mvcHelper.variableReplace(item.MessageId)">

hover over one element and addClass to other elem in Angular JS

Attempting with the below jQuery method: But this does not work in my Angular environment, assuming because I'm attempting to do this outside of angular JS scope methods, but I don't know how to implement this using Angular scope methods (new to angular) any advice?
$('.song-thumb .hover-play').on('mouseenter', function(e) {
var elem = $('section.suggestedAlbums img');
elem.trigger(e.type);
elem.addClass('hoverclass');
});
$('.song-thumb .hover-play').on('mouseleave', function(e) {
var elem = $('section.suggestedAlbums img');
elem.trigger(e.type);
elem.removeClass('hoverclass');
});
var count = 0;
$('section.suggestedAlbums img').hover(function() {
count++;
$('[remove]').html('<label remove><br>It triggers the hover event(' + count + ') too.<br></label>');
});
Full page code:
<script>
$('.song-thumb .hover-play').on('mouseenter', function(e) {
var elem = $('section.suggestedAlbums img');
elem.trigger(e.type);
elem.addClass('hoverclass');
});
$('.song-thumb .hover-play').on('mouseleave', function(e) {
var elem = $('section.suggestedAlbums img');
elem.trigger(e.type);
elem.removeClass('hoverclass');
});
var count = 0;
$('section.suggestedAlbums img').hover(function() {
count++;
$('[remove]').html('<label remove><br>It triggers the hover event(' + count + ') too.<br></label>');
});
</script>
<!-- <h2>{{trackListData.listTitle}}</h2>
--><div ng-repeat="track in trackListData.tracks track by $index " class="feature-item-homepage fade-animate-nostagger">
<div class="song-thumb" ng-class="{active: $root.currentPlaying.song_id == track.id}">
<!--3 Cases-->
<!--Not the song being played-->
<div class="hover-play" ng-if="$root.currentPlaying.song_id != track.id" ng-click="$root.playSong(track);">
<i class="fa fa-plus add-to-playlist" ng-init="playlistOption = false" ng-click="$root.initPlaylistOption($event, track.id); $event.stopPropagation();"></i>
<i class="fa fa-play play-song"></i>
<img src="img/producer_icon_white.png" class="prod_logo">
<div class="song-title" style="width: 80%;padding-top:25px;">
<a class="song-linking" href="#/song/{{track.id}}">
<h4>{{track.title}}</h4>
<h5>{{track.artist.user_name}}</h5>
</a>
</div>
</div>
<!--The current song but paused-->
<div class="hover-play" ng-if="$root.currentPlaying.song_id == track.id && !$root.isPlaying" play-music>
<i class="fa fa-plus add-to-playlist" ng-init="playlistOption = false" ng-click="$root.initPlaylistOption($event, track.id); $event.stopPropagation();"></i>
<i class="fa fa-play play-song"></i>
</div>
<!--The current song but playing-->
<div class="hover-play" ng-if="$root.currentPlaying.song_id == track.id && $root.isPlaying" pause-music>
<i class="fa fa-plus add-to-playlist" ng-init="playlistOption = false" ng-click="$root.initPlaylistOption($event, track.id); $event.stopPropagation();"></i>
<i class="fa fa-pause pause-song"></i>
</div>
<img ng-src="{{(track.albums[0].album_picture? $root.fileServer +'uploads/' + track.albums[0].album_picture:(track.artist.profile_picture? $root.fileServer +'uploads/' + track.artist.profile_picture:'img/defaultalbum.png'))}}" />
</div>
<!-- <div class="song-title-wrap">
<div class="song-title">
<a class="song-linking" href="#/song/{{track.id}}">
<h4>{{track.title}}</h4>
<h5>{{track.artist.user_name}}</h5>
</a>
</div>
</div> -->
</div>
Add a controller to a containing div:
<div ng-controller='MyController'>
Add ngMouseleave and ngMouseenter to the .song-thumb .hover-play element
<div class="hover-play" ng-if="$root.currentPlaying.song_id != track.id" ng-click="$root.playSong(track);" ng-mouseenter='state.hoverPlay=true;' ng-mouseleave='state.hoverPlay=false'>
Add the controller
angular.controller('MyController', [ '$scope', function ($scope) {
$scope.state = {
hoverPlay: false
};
}]);
Use ngClass to add/remove the class
<img ng-class="{ 'hoverclass': state.hoverPlay }" . . . >

Changing multiple images with JQuery

So here is the JQuery I am using
jQuery(document).ready(function($) {
$('.ltwitch').each(function () {
var tnick = $(this).data('tnick');
var span = $(this).next();
$.getJSON("https://api.twitch.tv/kraken/streams/"+tnick+".json?callback=?", function(c) {
if (c.stream == null) {
span.html("Offline");
} else {
span.html("Online");
}
});
});
});
And the HTML that was with it when I found it
<a class="ltwitch" href="http://www.twitch.tv/ifstudios" data-tnick="IFStudios">IFStudios</a> (<span>...</span>)
RoosterTeeth (...)
Now what I want to do, I have HTML that looks like this
<a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/sweet.png" class="img-responsive" alt="">
</a>
Basically when a channel becomes live I want to switch the img src from the image I have it set to, to the same image with -online on the end. So I can have multiple pictures on the website, but I can have the images change dependent on who is live and who isn't.
So if I have
<a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/sweet.png" class="img-responsive" alt="">
</a>
When her channel goes live, it will turn to
<a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/sweet-online.png" class="img-responsive" alt="">
Or if it was
<img src="img/portfolio/carrot.png"
it would turn to
<img src="img/portfolio/carrot-online.png"
Any ideas?
Try the below code
jQuery(document).ready(function($) {
$('.ltwitch').each(function () {
var tnick = $(this).data('tnick');
var span = $(this).next();
$.getJSON("https://api.twitch.tv/kraken/streams/"+tnick+".json?callback=?", function(c) {
var img = $(img-selector);
var source = img.attr('src');
if (c.stream != null) {
// Online
if(source.indexOf('.png') != -1){
source = source.replace(".png", "-online.png");
img.attr('src',source);
}
}
else{
// Offline
source.replace("-online", "");
img.attr('src',source);
}
});
});
});
Note: You have to pass the correct image selector to $(img-selector). Also call the same function again for refreshing

Categories