Checking image name using javascript - javascript

I'm changing the img src on click using javascript.
I'm trying to determine whether to switch on or off.
I'm testing the following:
var img_el = document.getElementById("on_off_img");
if ( img_el.src == 'img/on.png' ) {
img_el.src = 'img/off.png'
} else {
img_el.src = 'img/on.png'
}
My problem is that i never get a match - it looks like img_el.src returns the full URL... Is there a function to just test the actual filename instead of the full string to the file?
Or is there a better way to manage the click?

use indexOf() instead of comparing the src
e.g
var img_el = document.getElementById("on_off_img");
if ( img_el.src.indexOf('on.png') > -1) {
img_el.src = 'img/off.png'
} else {
img_el.src = 'img/on.png'
}

Yuo can always use indexOf:
if(img_el.src.indexOf('img/on.png') > -1){
img_el.src = 'img/off.png'
}else{
img_el.src = 'img/on.png'
}

To shorten this even more, you can use a ternary operator:
var img_el = document.getElementById("on_off_img"),
isOn = img_el.src.indexOf('on.png')>-1;
img_el.src = isOn ? 'img/off.png' : 'img/on.png';

You can use match statement aswell.
var img_el = document.getElementById("on_off_img");
if ( img_el.src.match("on.png"))
{
img_el.src = 'img/off.png'
} else
{
img_el.src = 'img/on.png'
}

Try using JQuery:
$("#on_off_img").click(function(){
if($(this)[0].nameProp == "on.png")
$(this).attr("src","img/off.png");
else
$(this).attr("src","img/on.png");
});

Related

simplify an if/else inside another else

I have a piece of code, i need to put an if/else inside an else to change the DOM of my view:
else {
this.selectedUser = this.user.find(b => b._id === userId)
this.onSelect.emit(this.selectedUser)
if (this.selectedUser.isConnected) {
(<HTMLImageElement>document.getElementById('user-state')).src = 'assets/imgs/userConnected.png'
} else {
(<HTMLImageElement>document.getElementById('user-state')).src
= 'assets/imgs/userDiscoonnected.png'
}
}
Is there a way to simplify this ? or make it more clean ?
only readable way I can think of is
else {
this.selectedUser = this.user.find(b => b._id === userId)
this.onSelect.emit(this.selectedUser)
(<HTMLImageElement>document.getElementById('user-state')).src =
this.selectedUser.isConnected
? 'assets/imgs/userConnected.png'
: 'assets/imgs/userDiscoonnected.png';
}
else {
this.selectedUser = this.user.find(b => b._id === userId)
this.onSelect.emit(this.selectedUser)
var imgPath = this.selectedUser.isConnected ? 'assets/imgs/userConnected.png' : 'assets/imgs/userDiscoonnected.png';
(<HTMLImageElement>document.getElementById('user-state')).src = imgPath;
}
A ternary operator looks nice.
You can use ? : to make a simpler if statement when you are comparing with a bool.
The statement on the left side of the ? is the condition to be fulfilled. To the left of the : you place the value of the variable if the condition is true. On the right side of the : you place what the value should be if the condition turns out to be false.
var src = this.selectedUser.isConnected ? 'assets/imgs/userConnected.png' : 'assets/imgs/userDiscoonnected.png';
<HTMLImageElement>document.getElementById('user-state')).src = src;

Input value equal/match to a any value in declared array with strings

I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if ($("input.reservationkey").val() === invalidkeyreservation) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
This is what .indexOf() is for.
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if (invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
Maybe you want to use includes:
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if (invalidkeyreservation.includes($("input.reservationkey").val())) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
Obs: If you are targeting to old browsers, there is polyfill available, or just use indexOf, as shown in the other answer.
You should be able to see if one of the elements in the array includes any of the string value, like so:
ES6
const invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if(invalidkeyreservation.some(key => key === $("input.reservationkey").val()) {
BootstrapDialog.show(return $content);
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
ES5
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if(invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
BootstrapDialog.show(return $content);
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
try like
var toCheck = $("input.reservationkey").val().trim().toUpperCase();
if (invalidkeyreservation.includes(toCheck )) {
//your code with the condition
}
Hope, it helps

Is there a better way to 'do nothing' in javascript if statement?

My url looks like this = https://studentscafe.com/menu/2
I'm trying to check whether or not it has 2 different url params...
1.) ?dinner=1
or
2.) &dinner=1
If #1 is present, do nothing
If #2 is present, do nothing
But if neither are present, default to adding ?dinner=1 to the url.
Is there a better way to have a default do nothing in an if statement? Fiddle here for example.
var path = 'https://studentscafe.com/menu/2';
if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is
} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}
Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1
Instead of
if (something) {
// do nothing
} else {
// do what you need
}
You can use
if (!something) {
// do what you need
}
In your case:
if (path.indexOf('?dinner=1') == -1 && path.indexOf('&dinner=1') == -1) {
path = path + '?dinner=1';
}
Using a regular expression and the ! negation operator, this can be rather simple:
var path = 'https://studentscafe.com/menu/2';
if (!/[?&]dinner=1/.test(path)) {
path += '?dinner=1';
}
console.log(path);
You can do this way.
var path = 'https://studentscafe.com/menu/2';
// Since there is no change to path if it contains either ?dinner=1 or &dinner=1
if (path.indexOf('dinner=1') >= 1) {
console.log('has dinner');
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
In modern JS you may simply do like
['?dinner=1','?dinner=2'].every(s => !path.includes(s)) && (path += '?dinner=1');

How to ignore extra parameters in URL?

< noob >
This following code works like a charm when I use the proper URL
www.exemple.com/?login
$(document).ready(function(){
function urlparam(){
var url = window.location.href.split('?')[1];
if (url == 'login' ) {
document.getElementById('loginMainContainer').style.display = 'block';
$('.login').triggerHandler('click');
} else if (url == 'signup' ){
document.getElementById('loginMainContainer').style.display = 'block';
$('.signup').triggerHandler('click');
}
}
urlparam()
});
But once I need to use this URL with other parameters (w/ mailchimp)
www.exemple.com/?login&utm_source=App+Accounts&utm_campaign=e94f95d4da-News_promo+email_English_2016
It really doesn't execute what I need.
Is there a way to ignore these extra parameters and execute properly my function?
Thanks for any help in advanced!
< /noob >
I would use a regular expression to handle this, it tests to match if the string starts with login or if it starts with signup.
var url = ('www.exemple.com/?login&utm_source=App+Accounts&utm_campaign=e94f95d4da-News_promo+email_English_2016').toString().split('?')[1];
if (url.match(/^login/ )) {
console.log('login');
} else if (url.match(/^signup/ )){
console.log('signup');
}
You just have to get all parameter and check if login exist.
var url="http://someurl.com?test=ok&machin=1234&login&azir=lol";
function parameterExist(url,paramName)
{
var parameters = url.split('?')[1].split('&');
for(var i=0;i<parameters.length;i++)
{
var paramNameUrl=parameters[i].split('=')[0];
if(paramNameUrl==paramName)
return true;
}
return false;
}
console.log(parameterExist(url,"login"));
console.log(parameterExist(url,"blabla"));

Javascript for conditional URL append or redirect based on window.location.href

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.
I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
Does exactly what I need it to but, well... not very graceful to say the least.
Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?
A (sort-of) refactoring of dthorpe's suggestion:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:
window.location.assign(window.location.href+='append2')
This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.
You could also reduce DOM lookups by setting window.location to a var.
The only reduction I can see is to pull out the redundant indexof calls into vars and then test the vars. It's not going to make any appreciable difference in performance though.
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
Kind of extendable code. Am i crazy?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location =window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}

Categories

Resources